Please, suppose that architecture:
public class Mammal
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Dog : Mammal
{
public int TailId { get; set; }
public Tail Tail { get; set; }
}
public class Bat : Mammal
{
public int WingId { get; set; }
public Wing Wing { get; set; }
}
public class Buffalo : Mammal
{
public virtual ICollection<Horn> Horns { get; set; }
}
public class Tail
{
public int Id { get; set; }
...
}
public class Wing
{
public int Id { get; set; }
...
}
public class Horn
{
public int Id { get; set; }
...
}
Now, my context:
public class MyContext : DbContext
{
public DbSet<Mammal> Mammals { get; set; }
}
So, I want to make ONLY ONE sql query, and include (and load) all nested entities, something like:
var query = myContext.Mammals
.IncludeIfTypeIs<Dog>(d => d.Tail)
.IncludeIfTypeIs<Bat>(b => b.Wing)
.IncludeIfTypeIs<Buffalo>(b => b.Horns)
...
...
;
I know that I can do that separately, but I don't want because I have many entities, and I need to minimize database requests.
I don't want use lazy loading because this will make many database requests also.
How to achieve that?
EF Core supports this in version 2.1 and higher. See the Github Issue here
var query = myContext.Mammals
.Include(d => (d as Dog).Tail)
.Include(b => (b as Bat).Wing)
.Include(b => (b as Buffalo).Horns)
This will include all the properties in one query.
Here is a link to the official documentation on this.
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