Using Include vs ThenInclude

c# entity-framework entity-framework-core

Question

I have been experimenting a little with EntityFramework, and after facing the error bellow, 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)
1
8
4/5/2018 10:25:33 AM

Popular Answer

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

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 whole 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 company and the "CountriesOfOperation" as related data then 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();
}
2
12/28/2019 10:37:55 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow