【问题标题】:Exception when trying to use `ThenInclude` in EF Core尝试在 EF Core 中使用“ThenInclude”时出现异常
【发布时间】:2016-11-30 13:30:27
【问题描述】:

我将 Entity Framework Core 与存储库模式一起使用,但遇到了一个问题。

我有 Customer、Company 和 Email 课程,其中隐藏了与此处无关的内容,如下所示:

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

映射被设置为Customer 和Company 之间存在一对一关联,而Company 和Email 之间存在一对多关联。

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

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

现在ThenInclude 出现了问题。如果我尝试使用这种方法,我最终会得到一个 execption 说 source 为空。

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

重点是:我有实体A、B、C,所以A 有B 之一,而B 有很多C,当我检索@ 987654340@ 我需要关联所有内容。

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

【问题讨论】:

  • 你就不能.Include(x =&gt; x.Company.Emails)吗?
  • 感谢@Will,使用此解决方案确实有效!顺便说一句,你知道为什么ThenInclude 不起作用吗?如果我理解了推荐方式的文档,但在这种情况下它根本不起作用。
  • 抱歉,不知道。没用过ThenInclue,不知道是怎么实现的。让我看看它并添加一个答案。

标签: c# .net entity-framework entity-framework-core .net-core


【解决方案1】:

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

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

(在 github repro 中搜索 ThenInclude 问题——有一个 TON。)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多