Mapping all derived types of a generic type in one table

405 views Asked by At

I have a question concerning EF Core 2.1

I have a base type, let's name it Customer, from which CustomerOld and CustomerNew are derived. These are automatically stored in one table, so far so good.

Now I have a generic type for mapping Customer to Product :

public class CustomerToProduct<T> where T : Customer 
{ 
    public int CustomerId { get; set; }
    public T Customer { get; set; }
    public int ProductId { get; set; }
    public Product Product { get; set; }
    ...
}

The derived types of CustomerToProduct have no specific properties. I just want to use them such as the Customer I access through the property CustomerToProduct.Customer is of the derived type.

I defined the DbSets for the derived types in my DbContext as follows, which of course leads to separate tables:

public class MyDbContext : DbContext 
{
    public DbSet<OldCustomerToProduct> OldCustomerToProducts { get; set; }
    public DbSet<NewCustomerToProduct> NewCustomerToProducts { get; set; }
    ...
}

How do I store all derived Types of CustomerToProduct<T> in the same table? How do I define the DbSets<>?

1

There are 1 answers

1
Norcino On

Yours looks like a good candedate for the mapping pattern TPH (Type per Hierarchy). You can read more here about the topic.