使用 Include 与 ThenInclude [英] Using Include vs ThenInclude

查看:85
本文介绍了使用 Include 与 ThenInclude的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 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"

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)

推荐答案

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆