问题描述
我一直在尝试使用 Entity Framework,在遇到下面的错误后,我尝试使用 ThenInclude 来解决它.
I have been experimenting a little with Entity Framework, and after facing the error below, I tried using ThenInclude to resolve it.
无法绑定传递给 Include 运算符的表达式[x].ModelA.ModelB"
但现在似乎我对它为什么解决了问题缺乏了解
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)
推荐答案
Include"适用于对象列表,但如果您需要获取多级数据,则ThenInclude";是最合适的.让我用一个例子来解释它.假设我们有两个实体,公司和客户:
"Include" works well with list of object, but if you need to get multi-level data, then "ThenInclude" is the best fit. Let me explain it with an example. Say we have two entities, Company and Client:
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 the entire 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 a Company with "CountriesOfOperation" as related data, 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();
}
这篇关于使用 Include 与 ThenInclude的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!