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)
The ThenInclude method moves the chaining level to the property included. It allows us to include related objects from the next level.
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.
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.
"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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With