gpt4 book ai didi

c# - 使用包含与 ThenInclude

转载 作者:太空狗 更新时间:2023-10-29 21:59:55 27 4
gpt4 key购买 nike

我一直在尝试使用 Entity Framework,在遇到以下错误后,我尝试使用 ThenInclude 来解决它。

The expression '[x].ModelA.ModelB' passed to the Include operator could not be bound

但现在我似乎对它解决问题的原因缺乏一些理解

这有什么区别:

.Include(x => x.ModelA.ModelB)

还有这个:

.Include(x => x.ModelA).ThenInclude(x => x.ModelB)

最佳答案

“Include”适用于对象列表,但如果您需要获取多级数据,那么“ThenInclude”是最合适的。让我用一个例子来解释它。假设我们有两个实体,公司和客户:

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; }
}

现在如果您只需要公司和该公司的整个客户列表,您可以只使用“包括”:

using (var context = new YourContext())
{
var customers = context.Companies
.Include(c => c.Clients)
.ToList();
}

但是如果你想要一个以“CountriesOfOperation”作为相关数据的公司,你可以在包括客户之后使用“ThenInclude”,如下所示:

using (var context = new MyContext())
{
var customers = context.Companies
.Include(i => i.Clients)
.ThenInclude(a => a.CountriesOfOperation)
.ToList();
}

关于c# - 使用包含与 ThenInclude,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49668851/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com