tacos_tacos_tacos
tacos_tacos_tacos

Reputation: 10585

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?)

Upvotes: 0

Views: 661

Answers (1)

Olav Nyb&#248;
Olav Nyb&#248;

Reputation: 11568

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

Upvotes: 2

Related Questions