我正在使用實體框架核心與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