2015-05-06 43 views
44

假设多次提到,我们有这种模式:包括在第二级

public class Tiers 
{ 
    public List<Contact> Contacts { get; set; } 
} 

public class Contact 
{ 
    public int Id { get; set; } 
    public Tiers Tiers { get; set; } 
    public Titre Titre { get; set; } 
    public TypeContact TypeContact { get; set; } 
    public Langue Langue { get; set; } 
    public Fonction Fonction { get; set; } 
    public Service Service { get; set; } 
    public StatutMail StatutMail { get; set; } 
} 

随着EF7我想检索来自层级表中所有提交的数据,从联系DATAS表格,Titre表格,TypeContact表格等等,只需一条指令。包含/ ThenInclude API我可以写这样的事:

_dbSet 
    .Include(tiers => tiers.Contacts) 
      .ThenInclude(contact => contact.Titre) 
    .ToList(); 

但滴度财产后,我不能包括其他的引用类似类型端子,索绪尔,Fonction ......包括方法提出了一种层级的对象,并ThenInclude建议Titre对象,但不是联系人对象。我如何包含我的联系人列表中的所有参考?我们可以通过单一指令来实现吗?

回答

64

.ThenInclude()将锁定最后的.ThenInclude()或最后的.Include()(以较近者为准)以拉入多个级别。要在同一级别包含多个兄弟姐妹,只需使用另一个.Include()链。格式化代码可以大大提高可读性。

_dbSet 
    .Include(tiers => tiers.Contacts).ThenInclude(contact => contact.Titre) 
    .Include(tiers => tiers.Contacts).ThenInclude(contact => contact.TypeContact) 
    .Include(tiers => tiers.Contacts).ThenInclude(contact => contact.Langue); 
    // etc. 
+2

好的,谢谢!我认为会有更好的解决方案;) –

+1

顺便说一句,这个问题激发了我创造问题[#2124](https://github.com/aspnet/EntityFramework/issues/2124) – bricelam

+0

为什么不:)这可能是一个好的特征 –