0

我有很多一对多的使用关系表导致这些关系的父母和孩子的关系并不在EF核心自动尚不支持:包括泛型列表属性的实体在ASP.NET的EntityFramework核心

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 => {从父子x in p select [x] .Child => FirstOrDefault()}'无效。表达式应该表示一个属性访问:'t => t.MyProperty'。

那么如何做到这一点呢?我想避免像手动获取实体这样不必要的查询:

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

回答

2

好像我误解了ThenInclude使用,因为它是指子实体。有其可能的一个列表来定义实体也加载在列表如下:

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

Visual Studio中具有显示在智能感知那些超载的问题,但它的存在并不会导致错误。

+3

'.ThenInclude'有两个重载(当遵循集合导航属性时)。一个用于'TPreviousProperty',另一个用于'ICollection '。对于一些人来说,Visual Studio似乎总是为“TPreviousProperty”变体显示intellisense,并且只显示集合扩展方法而不是模型。但是,如果在没有自动完成的情况下键入属性名称,那么它将选择正确的属性名称(就像你使用'.ThenInclude(p => p.Child)'所做的那样)并且不会显示编译器错误 – Tseng

+0

是的,这是问题所在, t首先注意到过载,因为它在智能感知中缺失。 – Lion

相关问题