entity-frameworkasp.net-coreef-core-2.0

Exclude derived entities from requests to the base class


I have this DbContext:

public class DataContext : DbContext
{
    public DbSet<Base> Bases {get;set}
    public DbSet<Sub> Subs {get;set}
}

Sub is a subclass of Base.

When I'm querying the list of Base entities like so:

Context.Bases.ToListAsync()

It returns me every entities, either Base or Sub.

How can I configure my model context to get only the entities that are of Base type and not the ones that derives from it.


Solution

  • You'd have to use OfType<T>:

    var basesOnly = await _context.Bases.OfType<Base>().ToListAsync();
    

    UPDATE

    Sorry, then. I could have sworn the above works, but it doesn't. The next best method I can think of is to simply filter out the types you don't want. It's not ideal, because it requires specifying all subtypes in your query, which then means you need to remember to update it if you add more subtypes.

    var basesOnly = await _context.Bases.Where(x => !(x is Sub)).ToListAsync();