Michael
Michael

Reputation: 13616

Renaming tables in DB in code first approach

I have database and multiple tables inside , I am using EF code first approach in my project.

At some point I need to change the names of some or maybe all tables in database.

What is the best way to implement it in code first approach?

Upvotes: 2

Views: 5987

Answers (2)

bubi
bubi

Reputation: 6491

You need to rename tables with migrations, i.e.

public override void Up()
{
    RenameTable("MyOldTableName", "MyNewTableName");
}

public override void Down()
{
    RenameTable("MyNewTableName", "MyOldTableName");
}

Then you need to change the table name on the mapping. If you use data annotation you can specify the table name with Table attribute

[Table("MyNewTableName")]
class MyEntity
{
    // props
}

If you use fluent interace

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
      modelBuilder.Entity<MyEntity>().ToTable("MyNewTableName");
}

Upvotes: 5

Stephen Brickner
Stephen Brickner

Reputation: 2602

This will change the table your entity maps to.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
      modelBuilder.Entity<User>().ToTable("Users");
}

Upvotes: 3

Related Questions