【发布时间】: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 的列表。但是ParentChild 的Child 实体不会自动加载,所以我只有孩子的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