gpt4 book ai didi

c# - 尝试在 EF Core 中使用 `ThenInclude` 时出现异常

转载 作者:行者123 更新时间:2023-11-30 14:49:29 26 4
gpt4 key购买 nike

我将 Entity Framework Core 与 Repository Pattern 一起使用,但遇到一个问题。

我有类 CustomerCompanyEmail,其中隐藏了与此处无关的内容,如下所示:

public class Email
{
public int EmailId { get; protected set; }

public string Address { get; protected set; }

public string Description { get; protected set; }

public Email(string address, string description)
{
if (string.isNullOrEmpty(address))
throw new ArgumentException(nameof(address));

if (string.isNullOrEmpty(description))
throw new ArgumentException(nameof(description));

this.Address = address;
this.Description = description;
}

protected Email() { }
}

public class Company
{
public int CompanyId { get; protected set; }

public IList<Email> Emails { get; set; }
}

public class Customer
{
public int CustomerId { get; protected set; }

public Company Company { get; set; }
}

设置映射,以便CustomerCompany 之间存在一对一关联,而 之间存在一对多关联公司电子邮件

然后我在 CustomersRepository 上创建了以下方法:

public IEnumerable<Customer> GetAll()
{
return _context.Set<Customer>()
.Include(x => x.Company)
.ThenInclude(x => x.Emails)
as IEnumerable<Customer>;
}

现在 ThenInclude 部分给出了一个问题。如果我尝试使用这种方法,我最终会得到一个提示说 source 为 null。

我已经检查了所有内容,但没有发现任何错误。看起来一切都写对了。

重点是:我有实体 ABC,所以 A 有其中之一B,而 B 有很多 C,当我检索 A 时,我需要获取所有关联的内容。

我在这里做错了什么?为什么我会收到此异常?

最佳答案

这似乎与 Github 上的错误报告有关 https://github.com/aspnet/EntityFramework/issues/2274

它被报告为 IOE,然后被报告为已修复,然后它作为 NRE 返回,就像您的异常一样。该问题表示已再次修复,但我不确定是哪个版本,也不知道您当前使用的是哪个版本。

(在 github repro 中搜索了 ThenInclude 问题——有一吨。)

听起来不稳定。远离它。您可以通过直接指定包含的完整路径来简单地完全避免该问题

muhCompaniesOrWhatevs.Include(x => x.Company.Emails);

关于c# - 尝试在 EF Core 中使用 `ThenInclude` 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38597690/

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