Include all the properties from all the inherited classes using EF Core

c# entity-framework entity-framework-core


When using EF6, I was using lazy loading so I never had this issue, but with EFCore, I don't know if this is possible with a single query.

I have the following class structure

class A { public B b; }
class B { public ICollection<C> list_c; }
class C { public ICollection<D> list_d; }
abstract class D { public long c_id; }
class Da { public E e; }
class Db { public F f; }

I need a list of all the D objects, but with access to their e and f properties respectively. I have a working query at the moment where I query _db.D over a list of c_id's that I fetch using the first half of the query below, but with that approach, I send one query to get all the c_id's and then one query per type (I have 4 types).

I was wondering if I can make it work with one call that looks something like this:

_db.As.Include(x => x.b)
      .ThenInclude(x => x.list_c)
      .ThenInclude(x => x.list_d)
      // some magic here
      .FirstOrDefaultAsync(x=> x.Id = model.Id);


At the moment this is how I make the list:

var a = await _db.As.Include(x => x.b)
                    .ThenInclude(x => x.list_c)
                    .FirstOrDefaultAsync(x=> x.Id = model.Id);

var result = await _db.Ds.OfType<Da>()
                         .Where(x=>a.b.list_c.Any(y=>y.Id == x.c_id))
                         .Where(x=>a.b.list_c.Any(y=>y.Id == x.c_id))
8/29/2017 6:27:28 PM

Popular Answer

I would advise against using Entity Framework Core if you have that option. Check the roadmap at - It currently doesn't have lazy loading to name of its (very annoying) shortcomings.

You can have your data access layer in a .NET 4.6 project and have your consuming project(s), even if the consuming is based on Core, reference that project without difficulty.

8/29/2017 7:59:48 PM

Related Questions


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