[英]Create nested object on Entity Framework Linq query
我正在尝试从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
设置ChildCategories=null
但是Ef查询不允许我在此级别分配Null值。
无法创建类型为'System.Collections.Generic.IEnumerable`1 [[[EntityModel.JobCategoryModel,EntityModel,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]“的空常量值。 在此上下文中仅支持实体类型,枚举类型或原始类型。
如果移除ChildCategories=null
,它将给出错误
发生内部异常:类型'EntityModel.JobCategoryModel'出现在单个LINQ to Entities查询中的两个结构不兼容的初始化中。 可以在同一查询的两个位置初始化一个类型,但前提是两个位置都设置了相同的属性,并且这些属性以相同的顺序设置。
第二种情况(删除ChildCategories=null
分配)听起来像是一个奇怪的EF规则,我想不出任何逻辑上的理由来施加约束。
无论如何,技巧(解决方法)是定义一个假的派生类,并将内部选择投射到该类(删除ChildCategories=null
)。 因此,以下工作:
class JobSubCategoryModel : JobCategoryModel { }
// ...
ChildCategories = x.SubCategory.Select(y => new JobSubCategoryModel
{
CategoryName = y.CategoryName,
Identifier = y.Identifier,
ImagePath = y.Images != null ? imagePath + "/" + y.Images.ImagePath : null,
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.