Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change column name on model creating in Entity Framework context class

I have a base class like that:

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 like that:

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 am using Entity Framework Code-First and configuring 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 run the program database and tables are created but primary key column names are Id for each table. I want the column name to be UserId or SchoolId.

Therefore I must configure entities on model creating to change column names with TableNameId

I could do this job as well:

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

Assume that I have hundreds of classes, I'll make configurations one by one for each entity so this is a huge waste of time.

How can I do this job dynamically using iterate or something else I don't know?

like image 950
test user Avatar asked May 03 '17 13:05

test user


1 Answers

You can use DbModelBuilder.Types<T> method to apply your custom convention on all BaseClass derived entities:

modelBuilder.Types<BaseClass>().Configure(c => 
    c.Property(e => e.Id).HasColumnName(c.ClrType.Name + "Id")
);
like image 159
Ivan Stoev Avatar answered Sep 25 '22 14:09

Ivan Stoev