【问题标题】:How to load all levels of object nested within a class, using Entity Framework 7 linq queries?如何使用 Entity Framework 7 linq 查询加载嵌套在类中的所有级别的对象?
【发布时间】:2016-05-17 20:48:22
【问题描述】:

我正在使用 Entity Framework 7 来映射我的应用程序的数据访问。

这是我正在使用的类的示例:

[Table("class1")]
public class Class1
{
    public int id { get; set; }
    public int randomProp1 { get; set; }
    public int randomProp2 { get; set; }

    public ICollection<Class2> collectionClass2 { get; set; }
    public ICollection<Class3> collectionClass3 { get; set; }
}

[Table("class2")]
public class Class2
{
    public int id { get; set; }
    public int idClass1 { get; set; }
    public int randomProp { get; set; }

    [ForeignKey("idClass1")]
    public Class1 class1 { get; set; }
}

[Table("class3")]
public class Class3
{
    public int id { get; set; }
    public int randomProp { get; set; }
    public int randomProp2 { get; set; }
    public int idClass2 { get; set; }

    [ForeignKey("idClass1")]
    public Class1 class1 { get; set; }

    public ICollection<Class4> collectionClass4 { get; set; }
}

[Table("class4")]
public class Class4
{
    public int id { get; set; }
    public int idClass3 { get; set; }
    public int randomProp4 { get; set; }

    [ForeignKey("idClass3")]
    public Class3 class3 { get; set; }
}

我正在尝试获得所有这些结构。为此,我有以下方法:

public List<Class1> GetAll()
{
    return _ctx.Class1
                .Include(x => x.collectionClass2)
                .Include(x => x.collectionClass3)
                .Include(x => x.collectionClass3.Select(c => c.collectionClass4))
                .ToList();
}

但是,当我尝试执行此方法时,出现以下异常:

EntityFramework.Core.dll 中出现“System.InvalidCastException”类型的异常,但未在用户代码中处理 附加信息:无法将“Remotion.Linq.Clauses.Expressions.SubQueryExpression”类型的对象转换为“System.Linq.Expressions.MemberExpression”类型。

如果我从查询中删除 .Include(x =&gt; x.collectionClass3.Select(c =&gt; c.collectionClass4)),它会检索数据,但嵌套在 class3 中的 class4 集合是一个 null 属性。

我也尝试使用 .ThenInclude(x =&gt; x.Select(c =&gt; c.collectionClass4)) 代替,正如我在互联网上的一些示例中看到的那样,但它得到了以下异常:

EntityFramework.Core.dll 中出现“System.ArgumentException”类型的异常,但未在用户代码中处理 附加信息:属性表达式 'x => {from Class3 c in x select [c].collectionClass4}' 无效。该表达式应表示属性访问:'t => t.MyProperty'。指定多个属性时使用匿名类型:'t => new { t.MyProperty1, t.MyProperty2 }'。

【问题讨论】:

    标签: c# .net entity-framework linq


    【解决方案1】:

    ThenInclude 位于Include 之后,表示嵌套对象也必须包含在内:

    .Include(x => x.collectionClass3)
        .ThenInclude(x => x.collectionClass4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      相关资源
      最近更新 更多