2016-07-26 50 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); 
相关问题