Programing

데이터 손실없이 Entity Framework 5 Code First 마이그레이션에서 데이터베이스 열의 이름을 바꾸는 방법은 무엇입니까?

crosscheck 2020. 11. 7. 09:01
반응형

데이터 손실없이 Entity Framework 5 Code First 마이그레이션에서 데이터베이스 열의 이름을 바꾸는 방법은 무엇입니까?


EF 5.0 Code First Migrations에서 성공적으로 실행되는 기본 ASP.NET MVC 4 템플릿을 얻었습니다. 그러나 모델 속성 이름을 업데이트하면 해당 테이블 열 데이터가 EF 5.0에서 삭제됩니다.

자동화 된 방식으로 데이터를 삭제하지 않고 테이블 열의 이름을 바꿀 수 있습니까?


수동으로 편집 마이그레이션의 위, 아래 방법은 사용하는 RenameColumn을 대체하는 방법 AddColumnDropColumn그것을 자동으로 생성하는.


이미 말했듯이 의 교체 AddColumnDropColumn그가 자동으로 생성됩니다 RenameColumn.

예:

namespace MyProject.Model.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class RenameMyColumn : DbMigration
    {
        public override void Up()
        {
            // Remove the following auto-generated lines
            AddColumn("dbo.MyTable", "NewColumn", c => c.String(nullable: false, maxLength: 50));
            DropColumn("dbo.MyTable", "OldColumn");

            // Add this line
            RenameColumn("dbo.MyTable", "OldColumn", "NewColumn");
        }

        public override void Down()
        {
            // Remove the following auto-generated lines
            AddColumn("dbo.MyTable", "OldColumn", c => c.String(nullable: false, maxLength: 50));
            DropColumn("dbo.MyTable", "NewColumn");

            // Add this line
            RenameColumn("dbo.MyTable", "NewColumn", "OldColumn");
        }
    }
}

이렇게 하면 마이그레이션을 요청할 있습니다RenameColumn .

[Column("NewName")]
public string OldName { get; set; }

생성 된 마이그레이션은 다음과 같습니다.

    public override void Up()
    {
        RenameColumn(table: "Schema.MyTable", name: "OldName", newName: "NewName");
    }

    public override void Down()
    {
        RenameColumn(table: "Schema.MyTable", name: "NewName", newName: "OldName");
    }

속성과 DB 열의 이름을 같게하려면 나중에 속성의 이름을 바꾸고 속성을 제거 할 수 있습니다 Column.


이제이 답변은 EF4.3에 대한 저의 지식을 기반으로하므로 마이그레이션이 EF5에서 거의 동일하게 작동하기를 바랍니다. 마이그레이션을 만든 후 Up 및 Down 메서드에 코드를 추가 할 수 있습니다. 오래된 재산의 삭제와 새로운 재산의 창조. 이 코드는 속성 데이터를 올바른 방향으로 이동해야합니다. 데이터 이동을 수행하기 위해 원시 SQL을 입력 할 수있는 SQL () 메서드로이 문제를 해결했습니다.

마이그레이션의 Up 방법에서 :

SQL("update [TheTable] set [NewColumn] = [OldColumn]");

그리고 Down () 메서드에서 :

SQL("update [TheTable] set [OldColumn] = [NewColumn]");

The disadvantage of this approach is that you might couple your code with the database you're working with at the moment (since you're writing raw DB-specific SQL). There might be other methods available for data movement as well.

More info available here: MSDN


Adding to Josh Gallagher's answer:

In some places the sp_RENAME syntax is described like this:

sp_RENAME 'TableName.[OldColumnName]' , '[NewColumnName]', 'COLUMN'

However, that will actually include the brackets in the new column name.

DbMigration's RenameColumn() method will probably do the same, so avoid using brackets when specifying the new column name.

Also, the auto-generated commands in Up() & Down() include DropPrimaryKey() and AddPrimaryKey() if the column being renamed is part of the primary key. These are not needed when using RenameColumn(). The underlying sp_RENAME automatically updates the primary key if needed.


you have 2 steps to rename column in code first migration

  1. The first step,you add ColumnAttribute above your column which are changed, and then update-database command

[Column("Content")]
public string Description { set; get; }

  1. The second step,

    • add-migration yournamechange command in order to create a partial class DbMigration.

    • add into up and down method here

RenameColumn("yourDatabase","name","newName");

public override void Up()
  {
        RenameColumn("dbo.your_database", "oldColumn",          
       "newColumn");
  }


public override void Down()
  {
        RenameColumn("dbo.your_database", "newColumn", 
        "oldColumn");
  }

Because when you connect, your database and model class will communicate via name_column at database and name_type at property method in model above.


like +Josh Gallagher said, you can use up() for doing things like:

public override void Up()
        {

            RenameColumn("dbo.atable","odlanem","newname");
            AddColumn("dbo.anothertable", "columname", c => c.String(maxLength: 250));

        }

i've found this a good help in gettin into migration ;)

참고URL : https://stackoverflow.com/questions/13104592/how-to-rename-a-database-column-in-entity-framework-5-code-first-migrations-with

반응형