假设我们有这个模型:
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,我想用一条指令从 Tiers 表中检索所有数据,从 Contact 表、Titre 表、TypeContact 表等中检索所有数据。使用 Include/ThenInclude API,我可以编写如下内容:
_dbSet
.Include(tiers => tiers.Contacts)
.ThenInclude(contact => contact.Titre)
.ToList();
但是在 Titre 属性之后,我不能包含其他引用,例如 TypeContact、Langue、Fonction ... Include 方法建议使用 Tiers 对象,然后 ThenInclude 建议使用 Titre 对象,而不是 Contact 对象。如何包含我的联系人列表中的所有引用?我们可以通过一条指令实现这一目标吗?
.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.
为了完整起见:
也可以通过 Include
如果它们不是集合属性直接包含嵌套属性,如下所示:
_dbSet
.Include(tier => tier.Contact.Titre)
.Include(tier => tier.Contact.TypeContact)
.Include(tier => tier.Contact.Langue);
不定期副业成功案例分享
var contacts = _dbSet.Include(tiers => tiers.Contacts);
contacts.ThenInclude(contact => contact.Titre);
contacts.ThenInclude(contact => contact.TypeContact);
contacts.ThenInclude(contact => contact.Langue);
那不行吗?Queryable
对象并且从不评估它们。contacts
只会有您分配给它的原始值。