【发布时间】: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 => x.Company.Emails)吗? -
感谢@Will,使用此解决方案确实有效!顺便说一句,你知道为什么
ThenInclude不起作用吗?如果我理解了推荐方式的文档,但在这种情况下它根本不起作用。 -
抱歉,不知道。没用过ThenInclue,不知道是怎么实现的。让我看看它并添加一个答案。
标签: c# .net entity-framework entity-framework-core .net-core