Entity Framework Table Per Class Inheritance

c# entity-framework entity-framework-6 inheritance sql

Accepted Answer

It is desirable to have a basic type that the entity and its history entity both inherit from:

public class BookingsContext : DbContext
{

    public DbSet<Booking> Bookings { get; set; }
    public DbSet<BookingHistory> BookingHistories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BookingBase>()
            .HasKey(p => p.BookingId)
            .Property(p => p.BookingId)
                       .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        modelBuilder.Entity<Booking>().Map(m =>
            {
                m.MapInheritedProperties();
                m.ToTable("Booking");
            });

        modelBuilder.Entity<BookingHistory>().Map(m =>
            {
                m.MapInheritedProperties();
                m.ToTable("BookingHistory");
            });
    }
}

By ToTable You designate mapping both entities to different tables. Additional to thatMapInheritedProperties instructs EF to also map all of the base type's properties to this table. the outcome is two entirely unique tables that can be addressed by two differentDbSet properties.

1
10/10/2014 3:19:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow