Search code examples
.netentity-frameworkcode-firstfluent-interface

How can I map a data member from an inherited class in multiple classes at once using Entity Framework Code First (Fluent API)?


If I have a class, say Entity, from which I create multiple classes. How can I do something like map the TimeStamp data member from the default column type of datetime to datetime2(7). I can map it individually like so:

protected override void OnModelCreating(DbModelBuilder mb)
{
  mb.Entity<Class1>()
    .Property(h => h.TimeStamp)
    .HasColumnType("datetime2")
}

But I would prefer to do it once for the Entity class and have it be applied to every class that inherits from Entity. If I do the above code but with Entity instead of Class1, I think it makes Entity a complex type. This puts everything in one table rather than what I want, which is TPC (Table per Concrete Type).

Here are example classes:

Entity.cs

public class Entity()
{
  public long ID { get; private set; }
  public DateTime TimeStamp { get; set; }
}

Class1.cs

public class Class1 : Entity
{
  public string SomeOtherDataMember1 { get; set; }
}

Class2.cs

public class Class2 : Entity
{
  public string SomeOtherDataMember2 { get; set; }
}

On a sort of side note (this is my next step that I have also looked into), how can I make the database recognize ID in Entity as the primary key for Class1 and Class2. Obviously ID is recognized as being in Class1 and Class2, but it is not the primary key. Similarly to with the TimeStamp, can I make it be the primary key for all inherited classes with one bit of code rather than writing it for each inherited class?


Solution

  • In the end I could not manage to map it with one call and did multiple. In order to do it in one call you need either TPH or TPT whereas I am using TPC and Entity does not have its own table.

    In terms of the side note it is currently not possible in EF Code First to make it the primary key and use TPC.