EntityFramework, Inherited Classes without Discriminator

c# entity-framework entity-framework-6

Question

Is it possible to use POCOs and EF to work with the following situation? I would like to have a Vehicles table, with some bool fields such as IsFast, IsVan, IsTruck, and then have a Vehicles class, with a FastVehicle, Van, Truck class that inherit from Vehicles class, without having their own tables, and without having a discriminator field?

Something like:

public class Vehicle
{
    public int Id {get; set;}
    public bool IsFast {get; set;}
    public bool IsTruck {get; set;}
    public bool IsVan {get; set;}
}

public class FastVehicle : Vehicle
{
    public FastVehicle(){
        IsFast = true;
    }
}

public class Van: Vehicle{
    public Van(){
        IsVan = true;
    }
}

public class Truck : Vehicle
{
    public Truck(){
        IsTruck = true;
    }
}

And then maybe in my DbContext have something like:

public virtual DbSet<Vehicle> Vehicles {get; set;}
public virtual DbSet<Van> Vans => (DbSet<Van>) Vehicles.Where(v => IsVan);
public virtual DbSet<Truck> Trucks => (DbSet<Truck>) Vehicles.Where(v => IsTruck);
public virtual DbSet<FastVehicle> FastVehicles => (DbSet<FastVehicle>) Vehicles.Where(v => IsFastVehicle);

Is something like this possible? Or is it a bad idea for some reason? How would I go about overriding OnModelCreating?

1
2
8/18/2016 2:43:01 PM

Popular Answer

If you dont have a discriminator or table for each class its not possible to distinguish your entities.

You can actually omit the bool properties if you don't need them in your domain model, because Entity Framework uses Table per Hierarchy as default to map inheritance. It will automatically create a discriminator column for you. If you add a truck object to your DbSet it will fill the discriminator colomn accordingly.

http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph

2
8/18/2016 3:07:16 PM


Related Questions





Related

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