How to dynamically change a column name when creating a model in an Entity Framework context class

I have a base class:

public class BaseClass : IEditableObject {

    public BaseClass() {

    }

    public Guid Id { get; set; }

    public void BeginEdit() {

    }
    public void CancelEdit() {

    }
    public void EndEdit() {

    }
}

And I have 2 derived classes:

public class User : BaseClass {

    [Column( "UserFirstName" )]
    public string FirstName {
        get;
        set;
    }

    [Column( "UserLastName" )]
    public string LastName {
        get;
        set;
    }
}

public class School : BaseClass {
    [Column( "SchoolName" )]
    public string Name {
        get;
        set;
    }
}

I use the Entity Framework Code-First and configure these classes in my context class:

public class MyContext : DbContext {

    public MyContext() : base() {
        Database.SetInitializer( new MigrateDatabaseToLatestVersion<MyContext, Configuration>() );
    }

    public DbSet<User> Users { get; set; }

    public DbSet<School> Schools { get; set; }

    protected override void OnModelCreating( DbModelBuilder modelBuilder ) {
        base.OnModelCreating( modelBuilder );
    }

}

When I start the program database and tables are created, but the column names of the primary key are Id for each table. I want the column name to be UserId or SchoolId .

Therefore, I have to configure the objects when creating the model to change the column names using TableNameId

I could do the job too:

modelBuilder.Entity<User>().Property( i => i.Id ).HasColumnName( "UserId" );
modelBuilder.Entity<School>().Property( i => i.Id ).HasColumnName( "SchoolId" );

Suppose I have hundreds of classes, I will make configurations one by one for each object, so this is a huge waste of time.

, - , ?

+4
2

DbModelBuilder.Types<T> BaseClass :

modelBuilder.Types<BaseClass>().Configure(c => 
    c.Property(e => e.Id).HasColumnName(c.ClrType.Name + "Id")
);
+4

. :

modelBuilder.Properties().Where(p => p.Name == "Id")
            .Configure(c => c.HasColumnName(c.ClrPropertyInfo.ReflectedType.Name + "Id"));
+3

Source: https://habr.com/ru/post/1676259/


All Articles