尝试在EF Core中使用`ThenInclude`时发生异常

use*_*696 3 .net c# entity-framework entity-framework-core .net-core

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

我有类CustomerCompany并且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; }
}
Run Code Online (Sandbox Code Playgroud)

该映射被设定成之间存在一个一对一的关联Customer,并Company同时有之间的一个一对多的关联CompanyEmail

CustomersRepository我那么创建了以下方法:

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

现在,ThenInclude这给了一个问题。如果我尝试使用此方法,最终将得到一个执行,说那source是空的。

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

整点是:我有实体ABC使A具有之一B,并B拥有众多的C,当我取回A我需要得到相关的一切。

我在这里做错了什么?为什么我收到此例外?

小智 5

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

它被报告为IOE,然后报告为已修复,然后又像您的例外一样以NRE的形式返回。这个问题说它已经被修复,但是我不确定是哪个版本,也不知道您当前正在使用哪个版本。

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

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

muhCompaniesOrWhatevs.Include(x => x.Company.Emails);
Run Code Online (Sandbox Code Playgroud)