我正在尝试运行此查询,我尝试获取类别和子类别
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();
目前字段ContinuumCategory.ContinuumSubCategories
的类型为List
,因此此查询会给我一个编译时错误,它无法将IEnumerable
转换为列表,当然它不能。
由于linq无法识别ToList
方法,所以我甚至无法在查询中使用它。
我可以通过将ContinuumCategory.ContinuumSubCategories
的类型更改为IEnumerable
来解决我的问题,但我已经在许多使用List.Add
方法的地方使用过此字段,因此我必须全部替换将方法添加到IEnumerable.Concat
,因此这可能很乏味。
是否有任何解决方法可以直接从linq查询中获取连续子类别列表?
修改
当我使用此查询时(在查询ContinuumSubCategories中使用ToList()
方法)
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();
我得到了这个例外
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.
答案 0 :(得分:0)
请勿在内部查询(ToList()
)
ContinuumSubCategories
将您的查询拆分为两部分,其间为ToList()
:
studentCont.ContinuumCategories = db.continuumcategorymasters
.Where(x => x.AssessmentId == assessmentId && x.ContinuumCategory != "other")
.ToList() // Fetch all the data from the db
.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();
有效吗?