Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Conditional Include by Entity Type

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?

like image 919
Alexandre TRINDADE Avatar asked Dec 01 '15 11:12

Alexandre TRINDADE


1 Answers

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.

like image 93
Jason Gallavin Avatar answered Oct 24 '22 04:10

Jason Gallavin