2016-07-26 119 views
1

我正在使用實體框架核心與Repository Pattern一起使用,我遇到了一個問題。嘗試在EF核心中使用'ThenInclude`時發生異常

我上課CustomerCompanyEmail其中,躲在這裏的東西不相關的,如下所示:

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,而CompanyEmail之間存在一對多關聯。

CustomersRepository然後我創建了以下方法:

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

那麼現在ThenInclude片給人一種問題。如果我嘗試使用這種方法,我最終得到一個執行文件,說source爲空。

我回顧了一切,但我沒有發現任何錯誤。似乎一切都寫得正確。

整點是:我有實體ABC使AB之一,B有很多的C,當我取回A我需要得到相關的一切。

我在這裏做錯了什麼?爲什麼我得到這個異常?

+1

你不能只是'.include(x => x.Company.Emails)'? – Will

+0

謝謝@威爾,它確實使用這個解決方案!順便說一下,你知道爲什麼'ThenInclude'不起作用嗎?如果我理解推薦方式的文檔,但在這種情況下,它根本行不通。 – user1620696

+0

對不起,不知道。從來沒有用過ThenInclue,不知道它是如何實現的。讓我們看看它,並添加一個答案。 – Will

回答

3

這似乎與此相關的bug報告在Github上https://github.com/aspnet/EntityFramework/issues/2274

據報道,作爲IOE的話報道固定,然後回來爲NRE,喜歡你的例外。該問題表示它已被再次修復,但我不確定哪個版本,我不知道您當前使用的是哪個版本。

(搜索在github上攝製ThenInclude問題 - 有一噸)。

聽起來很不穩定。遠離它。你可以簡單地通過直接指定包含的完整路徑來避免這個問題。

muhCompaniesOrWhatevs.Include(x => x.Company.Emails); 
相關問題