Home > other >  EF Core Inheritance Queries When Using a Single Table
EF Core Inheritance Queries When Using a Single Table

Time:04-10

Here's a .NET EF Core simplified scenario that I have been working on:

abstract class Colour
class Blue : Colour
class Green : Colour

class MyClass {
  public List<Colour> Colours { get; set; }
}

I have set the database up so that all colours are in one table:

public DbSet Blues { get; set; } public DbSet Greens { get; set; }

builder.Entity<Colour>()
.ToTable("Colours")
.HasDiscriminator<int>("ColourType")
.HasValue<Blue>((int)ColourType.Blue)
.HasValue<Green>((int)ColourType.Green);

When I am querying using LINQ, I can do the following:

List<Colours> MyList = MyClass.Colours;

The above query returns a list of all colour types.

My question is this. How do I do a direct LINQ query to retrieve all colours? It is not possible to do: DbContext.Colours. The options that I have are DbContext.Blues and DbContext.Greens. Another scenario is when I want to retrieve a Colour but I do not know what type it is.

CodePudding user response:

How do I do a direct LINQ query to retrieve all colours?

You've already configured Color as an entity in your DbContext, so you can siply write

var colors = db.Set<Color>().ToList();

Or add a DbSet for it:

  public DbSet<Blue> Blues { get; set; }
  public DbSet<Green> Greens { get; set; }
  public DbSet<Color> Colors{ get; set; }
  • Related