I am trying to run this query, where I try to fetch categories and there sub categories
studentCont.ContinuumCategories = db.continuumcategorymasters
.Where(x => x.AssessmentId == assessmentId && x.ContinuumCategory != "other")
.Select(x => new ContinuumCategory()
{
AssessmentId = x.AssessmentId,
ContinuumCategoryId = x.ContinuumCategoryId,
NativeAppid = x.NativeAppCategoryId,
score = 0,
ContinuumCategoryName = x.ContinuumCategory,
ContinuumSubCategories = x.continuumsubcategorymasters
.Select(csc => new ContinuumSubCategory
{
ContinuumSubCategoryId = csc.ContinuumSubCategotyId,
ContinuumSubCategoryName = csc.ContinuumSubCategotyName,
NativeAppsubid = csc.NativAppSubCategotyId
})
})
.ToList();
Currently the field ContinuumCategory.ContinuumSubCategories is of type List so this query gives me a compile time error that it cannot convert IEnumerable to list, ofcourse it cannot.
And as linq does not recognize ToList method so I cannot even use that inside my query.
I can solve my problem by changing the type of ContinuumCategory.ContinuumSubCategories to IEnumerable but I have already used this field in many places where it uses List.Add method so I will have to replace all the Add methods to IEnumerable.Concat, so this can be tedious.
Is there any workaround to directly get the list of continuum sub categories from linq query only?
Edit:
when I use this query(used ToList() method inside query for ContinuumSubCategories)
studentCont.ContinuumCategories = db.continuumcategorymasters
.Where(x => x.AssessmentId == assessmentId && x.ContinuumCategory != "other")
.Select(x => new ContinuumCategory()
{
AssessmentId = x.AssessmentId,
ContinuumCategoryId = x.ContinuumCategoryId,
NativeAppid = x.NativeAppCategoryId,
score = 0,
ContinuumCategoryName = x.ContinuumCategory,
ContinuumSubCategories = x.continuumsubcategorymasters
.Select(csc => new ContinuumSubCategory
{
ContinuumSubCategoryId = csc.ContinuumSubCategotyId,
ContinuumSubCategoryName = csc.ContinuumSubCategotyName,
NativeAppsubid = csc.NativAppSubCategotyId
}).ToList()
})
.ToList();
I get this exception
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[BusinessObjects.ContinuumSubCategory] ToList[ContinuumSubCategory]
(System.Collections.Generic.IEnumerable1[BusinessObjects.ContinuumSubCategory])' method, and this method cannot be translated into a store expression.
Don’t call
ToList()on the inner query (the one forContinuumSubCategories)Split your query into two parts with
ToList()in-between:Does it work?