我正在使用实体框架核心与Repository Pattern一起使用,我遇到了一个问题。尝试在EF核心中使用'ThenInclude`时发生异常
我上课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
片给人一种问题。如果我尝试使用这种方法,我最终得到一个执行文件,说source
为空。
我回顾了一切,但我没有发现任何错误。似乎一切都写得正确。
整点是:我有实体A
,B
,C
使A
有B
之一,B
有很多的C
,当我取回A
我需要得到相关的一切。
我在这里做错了什么?为什么我得到这个异常?
你不能只是'.include(x => x.Company.Emails)'? – Will
谢谢@威尔,它确实使用这个解决方案!顺便说一下,你知道为什么'ThenInclude'不起作用吗?如果我理解推荐方式的文档,但在这种情况下,它根本行不通。 – user1620696
对不起,不知道。从来没有用过ThenInclue,不知道它是如何实现的。让我们看看它,并添加一个答案。 – Will