简体   繁体   中英

Table Per Type Fluent Mapping in Entity Framework

With Entity Framework I can map related tables as a class inheritance and There are three different approaches to representing an inheritance hierarchy (by weblogs ):

  • Table per Hierarchy (TPH)
  • Table per Type (TPT)
  • Table per Concrete class (TPC)

The site mscblogs has a nice explanation for each one of these approaches.

I'm trying to understand how to map my tables using the approach TPT (Table per Type), but unlike the example of mscblogs , I need to do the mapping for fluent programming like:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

public class BillingDetailMap : EntityTypeConfiguration<BillingDetailEntity>
{
    public BillingDetailMap()
    {
        // ...
        this.Property(t => t.Number).HasColumnName("Number");
        // ...
    }    
}

// ...

I'm searching for several hours but I couldn't find anything. I found many examples how to do this with diagram , with attributes and others , but nothing with fluent api.

How to Mapping TPT in Entity Framework 4.1 Fluent API?

Mapping the Table-Per-Type (TPT) Inheritance

In the TPT mapping scenario, all types are mapped to individual tables. Properties that belong solely to a base type or derived type are stored in a table that maps to that type. Tables that map to derived types also store a foreign key that joins the derived table with the base table.

modelBuilder.Entity<Course>().ToTable("Course");  
modelBuilder.Entity<OnsiteCourse>().ToTable("OnsiteCourse");

Source

Check also my answer on previous question, hopefully it helps.

update complete example

public class AppContext : DbContext
{
    public DbSet<Item> Items { get; set; } // --> this dbset is required for TPT, if removed it will become TPCC
    public DbSet<Food> Books { get; set; }
    public DbSet<Book> Foods { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ItemMap());
        modelBuilder.Configurations.Add(new BookMap());
    }
}
public class ItemMap : EntityTypeConfiguration<Food>
{
    public ItemMap()
    {
        ToTable("Foods");
    }
}
public class BookMap : EntityTypeConfiguration<Book>
{
    public BookMap()
    {
        ToTable("Books");
    }
}
public abstract class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Food : Item { }
public class Book : Item { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM