Search code examples
c#entity-frameworkinheritancefluent-interface

Use Table-Per-Type for all EF context classes with Fluent API


Currently, if I want to use Fluent API to stipulate the table-per-type inheritance strategy, I have to do the following:

modelBuilder.Entity<User>().ToTable("User");
modelBuilder.Entity<ContentItem>().ToTable("ContentItem");
modelBuilder.Entity<MarketItem>().ToTable("MarketItem");

If I somehow forget to add a command for a new inherited entity it will break my schema.

What I would like to do, in pseudo code, is:

foreach (ModelType T in AllModelTypes)
{
    modelBuilder.Entity<T>().Table(T.ToString());
}

Is there anything built-in to EF Fluent API that accomplishes this?

If not, is there a way I can achieve the foreach loop as described above (iterating over types?)


Solution

  • Using Entity Framework 6 this should do what you want:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);    
            modelBuilder.Types().Configure(t =>t.ToTable(t.ClrType.Name));
        }
    

    Update

    Here's a link to a msdn article on Custom Code First Conventions