ChatGPT解决这个技术问题 Extra ChatGPT

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?


v
vivek nuna

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

BTW, this question inspired me to create issue #2124
why not: var contacts = _dbSet.Include(tiers => tiers.Contacts); contacts.ThenInclude(contact => contact.Titre); contacts.ThenInclude(contact => contact.TypeContact); contacts.ThenInclude(contact => contact.Langue); Wouldn't that work?
@Doug No, you'd be creating new Queryable objects each time and never evaluating them. contacts would only ever have the original value you assigned to it.
This solution works but the resulting SQL statement results in three LEFT JOINs with Contacts (at least in my experience). That is terribly inefficient. There has to be a better way.
For new seekers: in 2020, with EF Core 3.1, my test with the accepted solution worked fine and it did not resulted in 3 left joins.
R
Risadinha

For completeness' sake:

It is also possible to include nested properties directly via Include in case they are not collection properties like so:

_dbSet
    .Include(tier => tier.Contact.Titre)
    .Include(tier => tier.Contact.TypeContact)
    .Include(tier => tier.Contact.Langue);

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now