【问题标题】:Create nested object on Entity Framework Linq query在 Entity Framework Linq 查询上创建嵌套对象
【发布时间】: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


【解决方案1】:

第二种情况(删除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,
})

【讨论】:

  • 我做了同样的伎俩。我工作。我为子类别创建了另一个类。
  • 我知道是因为我在发布之前已经尝试过解决方案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多