【问题标题】:Include Entity of generic list property in ASP.NET EntityFramework Core在 ASP.NET EntityFramework Core 中包含通用列表属性的实体
【发布时间】:2016-10-30 12:08:41
【问题描述】:

我使用关系表在父母和孩子之间建立了多对多关系,因为 EF Core 尚未自动支持这些关系:

class Parent{
    [Key]
    public int Id{get;set;}
    public List<ParentChild> ParentChilds{get;set;}
}

class Child{
    [Key]
    public int Id{get;set;}
    public List<ParentChild> ParentChilds{get;set;}
}

class ParentChild{
    public int ParentId{get;set;}
    public Parent Parent{get;set;}
    public int ChildId{get;set;}
    public Child Child{get;set;}
}

为了编辑父母,我需要得到他所有的孩子。似乎是Include() 的工作

var db = new MyDbContext();
var parentWithChilds = db.Parents.Include(p => p.ParentChilds)
    .FirstOrDefault(p => p.Id == 1);

这给了我ParentChild istances 的列表。但是ParentChildChild 实体不会自动加载,所以我只有孩子的Id,但没有我需要的Child 对象本身。我发现ThenInclude 似乎是为这种情况设计的,从this 等示例中我做了以下操作:

var parentWithChilds = db.Parents.Include(p => p.ParentChilds)
    .ThenInclude(p => p.Select(x => x.Child))
    .FirstOrDefault(p => p.Id == 1);

但它会抛出异常:

属性表达式'p => {from ParentChild x in p select [x].Child => FirstOrDefault()}' 无效。该表达式应表示属性访问:'t => t.MyProperty'。

那么如何做到这一点呢?我想避免不必要的查询,例如以这种方式手动获取实体:

user.ParentChilds.ForEach(pc => pc.Child = db.Childs.FirstOrDefault(x => x.Id == pc.ChildId));

【问题讨论】:

    标签: c# entity-framework asp.net-core entity-framework-core generic-list


    【解决方案1】:

    似乎我误解了ThenInclude 的用法,因为它指的是子实体。有一个列表可以定义要加载的实体,如下所示:

    var parentWithChilds = db.Parents.Include(p => p.ParentChilds)
        .ThenInclude(p => p.Child)
        .FirstOrDefault(p => p.Id == 1);
    

    Visual Studio 在智能感知中显示这些过载时存在问题,但它存在并且不会导致错误。

    【讨论】:

    • .ThenInclude 有两个重载(当遵循集合导航属性时)。一种用于TPreviousProperty,另一种用于ICollection&lt;TPreviousProperty&gt;。对于某些人来说,Visual Studio 似乎总是为TPreviousProperty 变体显示智能感知,并且只显示集合扩展方法而不是模型。但是在没有自动完成的情况下键入属性名称时,它会选择正确的名称(就像您使用 .ThenInclude(p =&gt; p.Child) 所做的那样,并且不会显示编译器错误。
    • 是的,这就是问题所在,我没有首先注意到过载,因为它在智能感知中丢失了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多