【发布时间】:2016-04-12 08:51:24
【问题描述】:
我正在尝试从 Ef 查询中获取嵌套数据。
var imagePath = ImagePath.GetImagePath();
var data = repos.JobCategoryRepo.GetMany(x => x.Parent == null).Select(x => new JobCategoryModel
{
CategoryName = x.CategoryName,
Identifier = x.Identifier,
ImagePath = x.Images != null ? imagePath+"/"+x.Images.ImagePath : null,
ChildCategories = x.SubCategory.Select(y => new JobCategoryModel
{
CategoryName = y.CategoryName,
Identifier = y.Identifier,
ImagePath = y.Images != null ? imagePath + "/" + y.Images.ImagePath : null,
ChildCategories=null
})
});
还有repos.JobCategoryRepo.GetMany(x => x.Parent == null)
将返回 IQueryable
据我所知,在第二级,没有 ChildCategories,所以在第二级,我设置了ChildCategories=null
但 Ef 查询不允许我在此级别分配 Null 值。
无法创建类型为空的常量值 'System.Collections.Generic.IEnumerable`1[[EntityModel.JobCategoryModel, EntityModel,版本=1.0.0.0,文化=中性,PublicKeyToken=null]]'。 仅支持实体类型、枚举类型或原始类型 在这种情况下。
如果删除ChildCategories=null
那么它会报错
发生内部异常:类型 'EntityModel.JobCategoryModel' 出现在两个结构上 单个 LINQ to Entities 查询中的不兼容初始化。一种 type 可以在同一个查询中的两个地方初始化,但前提是 两个地方都设置了相同的属性,这些属性是 以相同的顺序设置。
【问题讨论】:
-
只是不要放在select里,只赋值
CategoryName等 -
你的意思是,创建匿名对象而不是创建
JobCategoryModel对象? -
不,填写categoryname,identifier & imagepath但是不要对ChildCategories做任何事情,这样就不会报错。
-
使用 'new JobCategoryModel[] { }' 类型的空数组而不是修复 'null' 值是否有帮助?或者使用可枚举类型 'Enumerable.Empty
()'。 -
@AmitKumar 不知道它会引发错误,因为您在查询中以不同的方式使用它两次,我每天都学到新东西 :) 您必须使用 Tim 的解决方案案例
标签: c# asp.net-mvc entity-framework linq