使用包含vs然后包含 [英] Using Include vs ThenInclude
问题描述
我一直在尝试使用EntityFramework,在遇到下面的错误之后,我尝试使用ThenInclude来解决它。
I have been experimenting a little with EntityFramework, and after facing the error bellow, i tried using ThenInclude to resolve it.
The传递给Include运算符的表达式'[x] .ModelA.ModelB'无法绑定
The expression '[x].ModelA.ModelB' passed to the Include operator could not be bound
但是现在看来我缺乏理解为何能解决问题
But now it seems i lack some understanding of why it did solve the problem
这有什么区别?
.Include(x => x.ModelA.ModelB)
这:
.Include(x => x.ModelA).ThenInclude(x => x.ModelB)
推荐答案
包含可以很好地与对象列表配合使用,但是如果需要获取多级数据那么 ThenInclude是最合适的。让我用一个例子来解释。假设我们有两个实体组织和客户,
"Include" work well with list of object but if need to get multi-level data then "ThenInclude" is the best fit. Let me explain it with an example. Say we have two entities Organization and Clients,
public class Company
{
public string Name { get; set; }
public string Location { get; set; }
public List<Client> Clients {get;set;}
}
public class Client
{
public string Name { get; set; }
public string Domains { get; set; }
public List<string> CountriesOfOperation { get; set; }
}
现在,如果您只需要公司和该公司的整个客户列表,就可以只需使用包含,
Now if you want just companies and whole client list of that company you can just use "Include",
using (var context = new YourContext())
{
var customers = context.Companies
.Include(c => c.Clients)
.ToList();
}
但是如果要将公司和 CountriesOfOperation作为相关数据,则可以在包含如下所示的客户端之后,使用 ThenInclude。
But if you want company and the "CountriesOfOperation" as related data then you can use "ThenInclude" after including Clients like below,
using (var context = new MyContext())
{
var customers = context.Companies
.Include(i => i.Clients)
.ThenInclude(a => a.CountriesOfOperation)
.ToList();
}
这篇关于使用包含vs然后包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!