Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Include vs ThenInclude

I have been experimenting a little with Entity Framework, and after facing the error below, I tried using ThenInclude to resolve it.

The expression '[x].ModelA.ModelB' passed to the Include operator could not be bound

But now it seems I lack some understanding of why it did solve the problem

What's the difference between this:

.Include(x => x.ModelA.ModelB)

And this:

.Include(x => x.ModelA).ThenInclude(x => x.ModelB)
like image 719
Uentee Avatar asked Apr 05 '18 09:04

Uentee


People also ask

When to use ThenInclude in c#?

The ThenInclude method moves the chaining level to the property included. It allows us to include related objects from the next level.

What is include in Entity Framework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.

What is include in LINQ query C#?

Introduction to LINQ Include. LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include() which point towards similar entities must read from the database to get in a single query.


2 Answers

"Include" works well with list of object, but if you need to get multi-level data, then "ThenInclude" is the best fit. Let me explain it with an example. Say we have two entities, Company and Client:

public class Company
{
    public string Name { get; set; }

    public string Location { get; set; }

    public List<Client> Clients {get;set;}
}

 public class Client
 {
    public string Name { get; set; }

    public string Domains { get; set; }

    public List<string> CountriesOfOperation { get; set; }
 }

Now if you want just companies and the entire client list of that company, you can just use "Include":

using (var context = new YourContext())
{
  var customers = context.Companies
    .Include(c => c.Clients)
    .ToList();
}

But if you want a Company with "CountriesOfOperation" as related data, you can use "ThenInclude" after including Clients like below:

using (var context = new MyContext())
{
   var customers = context.Companies
    .Include(i => i.Clients)
      .ThenInclude(a => a.CountriesOfOperation)
    .ToList();
}
like image 91
Vijayanath Viswanathan Avatar answered Oct 24 '22 01:10

Vijayanath Viswanathan


The difference is that Include will reference the table you are originally querying on regardless of where it is placed in the chain, while ThenInclude will reference the last table included. This means that you would not be able to include anything from your second table if you only used Include.

like image 27
Kake_Fisk Avatar answered Oct 24 '22 01:10

Kake_Fisk