[英]Entity Framework Core Include/ThenInclude to get the data
I have tables in my database with the following one-to-many relations:我的数据库中有以下一对多关系的表:
a -> b
b -> c
b -> d
which are mapped to corresponding navigational properties in the model.它们映射到 model 中的相应导航属性。
I want to get data from "a" with all related data from "b, c, d".我想从“a”获取数据以及“b,c,d”的所有相关数据。
If I try:如果我尝试:
dbcontext.a.Include(x => x.b)
.ThenInclude(x => x.c)
.ThenInclude(x => x.d)
I get an error because this implies a relationship c -> d
(instead of b -> d
).我收到一个错误,因为这意味着关系c -> d
(而不是b -> d
)。
Then, if I try:然后,如果我尝试:
dbcontext.a.Include(x => x.b)
.ThenInclude(x => x.c)
.Include(x => x.d)
I get an error because this implies a relationship a -> d
(instead of b -> d
).我收到一个错误,因为这意味着关系a -> d
(而不是b -> d
)。
I'd appreciate help on how to correctly chain the methods.我很感激有关如何正确链接方法的帮助。
Try this if you use net5如果你使用 net5 试试这个
dbcontext.a.Include(x => x.b)
.ThenInclude(x => x.c)
.Include(x => x.b)
.ThenInclude(x => x.d)
Or to avoid repeating you can try ( was tested by @Marko )或者为了避免重复,您可以尝试(由@Marko 测试)
dbcontext.a.Include(x => x.b)
.ThenInclude(x => x.c)
.Include(x => x.b.d)
but I prefer to use this syntax (fits for all versions)但我更喜欢使用这种语法(适用于所有版本)
dbcontext.a.Include(x => x.b)
.ThenInclude(x => x.c)
.Include("b.d")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.