Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

asp.net core mvc - Include several references on the second level

Assume we have this model :

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

and

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; }
}

With EF7 I would like to retrieve all data from the Tiers table, with data from the Contact table, from the Titre table, from the TypeContact table and so on ... with one single instruction. With Include/ThenInclude API I can write something like this :

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

But after Titre property, I can't include others references like TypeContact, Langue, Fonction ... Include method suggests a Tiers objects, and ThenInclude suggests a Titre object, but not a Contact object. How can I include all references from my list of Contact? Can we achieve this with one single instruction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.ThenInclude() will chain off of either the last .ThenInclude() or the last .Include() (whichever is more recent) to pull in multiple levels. To include multiple siblings at the same level, just use another .Include() chain. Formatting the code right can drastically improve readability.

_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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...