Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core Inheritance creating child tables

public class Product
{
    public string Name { get; set; }
    public int Qty { get; set; }
    public decimal Price { get; set; }``
}
public class CartItem : Product
{
    public int CartItemId { get; set; }

    public string CartId { get; set; }
}
public class OrderLine : Product
{
    public int OrderLineId { get; set; }

    public int OrderId { get; set; }
}

public class Kititem : Product
{
    public int KititemId { get; set; }

    public int OrderId { get; set; }
}

public class SampleContext : DbContext
{
    public DbSet<CartItem> CartItems { get; set; }
    public DbSet<OrderLine> OrderLines { get; set; }
    public DbSet<Kititem> Kititems { get; set; }
}

As you can see in this I am not including the parent class Product in the DbContext, and when doing the migrations it creates a table for each derived class with all the properties form the parent class, and it does not create the parent class because is not included in the Dbcontext, for me it was what I was exptecting and is working, and I am happy with it so far Mi question is if that is a bad practice and maybe I am not using ef core Inheritance the way I can take all the advantages ? I am confuse and want to start a new project and do it the best way, so I don't have to redo it again

like image 906
Longinos Ruvalcaba Avatar asked Dec 06 '18 17:12

Longinos Ruvalcaba


1 Answers

What you are using is called "base class" as opposed to "base entity", i.e. class participating in database model inheritance.

You are not forced to use database inheritance at all. Moreover EF Core currently supports only Table per Hierarchy (TPH) strategy, which is not the best if you have many derived entities with many different properties (because all the data is stored in a single table).

In other words, there is nothing wrong to not use database inheritance. The only benefit of database inheritance is if you need polymorphic queries, i.e. queries that return Products of different types. It's possible to do such queries w/o database inheritance using Union / Concat LINQ operator, but they won't be efficient due to current EF Core lack of translating such queries to SQL, so they always use client evaluation.

Of course this will be improved in some future EF Core version (as well as support for other inheritance strategies), so the main question should be - do you need such queries. If you don't, then your approach of not using database inheritance is just fine. If you do, then decide which is more suitable for your needs - manual Concat or a single table with a lot of columns.

like image 88
Ivan Stoev Avatar answered Sep 18 '22 17:09

Ivan Stoev