[英]Include Entity of generic list property in ASP.NET EntityFramework Core
I have a many-to-many relation between parents and childs using a relation table cause those relations are not automatically supported in EF Core yet: 我使用关系表在父母与孩子之间建立了多对多关系,因为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;}
}
For editing the parent, I need to get ALL of his childs. 为了编辑父母,我需要得到他所有的孩子。 Seems like a job for
Include()
似乎是
Include()
var db = new MyDbContext();
var parentWithChilds = db.Parents.Include(p => p.ParentChilds)
.FirstOrDefault(p => p.Id == 1);
This gave me the list of ParentChild
istances. 这给了我
ParentChild
实例的列表。 But the Child
entity of ParentChild
isn't loaded automatically, so I only have the Id of the child, but not the Child object itself which is needed for me. 但是
ParentChild
的Child
实体不会自动加载,因此我只有孩子的ID,而没有我需要的Child对象本身。 I found ThenInclude
which seems to be designed for such cases and from examples like this I did the following: 我发现
ThenInclude
这似乎是专为这种情况下,并从类似的例子这个我做了以下内容:
var parentWithChilds = db.Parents.Include(p => p.ParentChilds)
.ThenInclude(p => p.Select(x => x.Child))
.FirstOrDefault(p => p.Id == 1);
But it throws an exception: 但这会引发异常:
The property expression 'p => {from ParentChild x in p select [x].Child => FirstOrDefault()}' is not valid.
属性表达式“ p => {从p中的ParentChild x选择[x] .Child => FirstOrDefault()}”无效。 The expression should represent a property access: 't => t.MyProperty'.
该表达式应表示属性访问:“ t => t.MyProperty”。
So how can this be done? 那怎么办呢? I would like to avoid unnecessary queries like fetching the entity manually this way:
我想避免不必要的查询,例如以这种方式手动获取实体:
user.ParentChilds.ForEach(pc => pc.Child = db.Childs.FirstOrDefault(x => x.Id == pc.ChildId));
Seems like I misunderstand the usage of ThenInclude
since it refers to the sub-entity. 似乎我误解了
ThenInclude
的用法,因为它是指子实体。 Having a list its possible to define the entity to load also on lists like this: 有了列表,就可以定义要在这样的列表上加载的实体:
var parentWithChilds = db.Parents.Include(p => p.ParentChilds)
.ThenInclude(p => p.Child)
.FirstOrDefault(p => p.Id == 1);
Visual Studio has issues showing those overload in intellisense, but its there and wouldn't result in errors. Visual Studio有一些问题,它们显示出智能感知中的那些重载,但在那里并不会导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.