Entity Framework 6 & TPH inheritance: Map properties with the same name to same column by default
Asked Answered
I

1

10

As of EF6 it is possible to do something like this when configuring Entity mappings using Table Per Hierarchy inheritance:

public class MyContext : DbContext 
{
    public DbSet<Device> Devices { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ABatteryPoweredDevice>().Property(c => c.BatteryLevel).HasColumnName("BatteryLevel");
        modelBuilder.Entity<ADifferentBatteryPoweredDevice>().Property(c => c.BatteryLevel).HasColumnName("BatteryLevel");
    }
}

BatteryLevel is not part of the Device base class- it is a property of the derived classes implemented to fulfill an interface contract.

Is it possible to make this the default behavior as opposed to having to add a new mapping for each derived class?

Inhalant answered 24/10, 2013 at 21:56 Comment(0)
I
13

Used Custom Code First Conventions, which are available from EF6 onwards, to sort this out:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //your code before
        modelBuilder.Properties().Configure(prop => prop.HasColumnName(prop.ClrPropertyInfo.Name));
        //your code after
    }

This maps properties with the same name in different derived types to the same table column without explicit calls like those mentioned in the question.

Inhalant answered 18/3, 2014 at 18:16 Comment(1)
Is there any way to configure this only for a table in EF6? I try to use Properties<Table>() and even create a derived class consisting of every columns in the DB table to use Properties<FullTable>(), but nothing works. Setting Properties() would affect all tables in the DB and I don't want that to override existing configuration.Revealment

© 2022 - 2024 — McMap. All rights reserved.