Entity Framework 마이그레이션 업데이트 데이터베이스가 성공했지만 데이터베이스 열이 추가되지 않았습니다.

StackOverflow https://stackoverflow.com//questions/24007883

문제

SQL Server 2008 R2와 함께 VS2012에서 Entity Framework를 사용하고 있습니다.마이그레이션이 활성화되어 있고 문자열 필드(예:DropboxUrl)을 내 데이터베이스 클래스 중 하나(예:디자인).

// Design.cs

public class Design
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

        [StringLength(Constants.DESIGN_NAME_MAX_LENGTH)]
        public string Name { get; set; }

        [StringLength(Constants.DESIGN_DESC_MAX_LENGTH)]
        public string Description { get; set; }

        public ItemDate Dates { get; set; }

        public string DropboxUrl { get; set; } // Added this line
    }

// SedaContext.cs:

public class SedaContext : DbContext
    {
        public DbSet<Company> Companies { get; set; }

        public DbSet<Design> Designs { get; set; }
…
}


// Global.aspx
protected void Application_Start()
        {

            // Application initialize
            // https://stackoverflow.com/questions/3600175/the-model-backing-the-database-context-has-changed-since-the-database-was-crea

            Database.SetInitializer<SedaContext>(null);

패키지 관리자 콘솔에서 PM> Update-Database를 실행할 때 데이터베이스에 이미 '회사'라는 객체가 있다고 불평합니다.'회사'는 업데이트하려는 기존 데이터베이스에 현재 존재하는 테이블입니다.

즉.

PM> update-database -verbose
Using StartUp project 'UI'.
Using NuGet project 'UI'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'SedaDev' (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Applying automatic migration: 201405311730564_AutomaticMigration.
CREATE TABLE [dbo].[Companies] (
    [Id] [uniqueidentifier] NOT NULL DEFAULT newsequentialid(),
    [Name] [nvarchar](max),
    [Description] [nvarchar](max),
    [Owner_UserId] [int],
    CONSTRAINT [PK_dbo.Companies] PRIMARY KEY ([Id])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Companies' in the database.
...
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:fa9e9e62-aba0-435f-9309-e9fc8fbe19d5

There is already an object named 'Companies' in the database.

시도 1: 이 오류를 검색한 후 다음 해결 방법을 발견했습니다.http://christesene.com/entity-framework-4-3-code-first-with-automatic-migrations/

내가 먼저 뛰는 걸 추천했어

PM> Add-migration initial

Scaffolding migration 'initial'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration initial' again.

그리고 Up/Down 메서드를 제거했습니다.

즉.DropboxUrl이 Up 메서드의 필드인 것을 볼 수 있었지만 제안된 대로 제거했습니다.

public override void Up()
        {
/*
    CreateTable(
                "dbo.Companies",
                c => new
                    {
                        Id = c.Guid(nullable: false, identity: true),
                        Name = c.String(),
                        Description = c.String(),
                        Owner_UserId = c.Int(),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.UserProfiles", t => t.Owner_UserId)
                .Index(t => t.Owner_UserId);
...
  CreateTable(                "dbo.Designs",
                c => new
                    {
                        Id = c.Guid(nullable: false, identity: true),
                        Name = c.String(maxLength: 100),
                        Description = c.String(maxLength: 1000),
                        Dates_Create = c.DateTime(nullable: false),
                        Dates_LastUpdate = c.DateTime(nullable: false),
                        DropboxUrl = c.String(),
                        Project_Id = c.Guid(),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.Projects", t => t.Project_Id)
                .Index(t => t.Project_Id);
*/
        }

그 후 update-database를 다시 실행했는데 성공한 것 같습니다.

PM> update-database -verbose
Using StartUp project 'UI'.
Using NuGet project 'UI'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'SedaDev' (DataSource: phobos.spxis.com, Provider: System.Data.SqlClient, Origin: Configuration).
Applying explicit migrations: [201406020449030_initial].
Applying explicit migration: 201406020449030_initial.
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])

VALUES (N'201406020449030_initial', N'Delecs.Seda.DataAccess.Migrations.Configuration',  0x1F8B0800000000000400ED1DCB72DCB8F19EAAFCC3D49C92544523D9F166
...
7B7C117028FAD9D8632C54E5F87C13A0D36590D83B7A73FA9F8AD368F7FFE3F0347EA807B340100 , N'6.0.2-21211')
Running Seed method

문제 1: 업데이트 후에 내 테이블이 변경되지 않았습니다(예:코드에 있는 DropboxUrl 열은 데이터베이스에 추가되지 않았습니다.

문제 2: 그리고 데이터베이스를 초기 상태로 되돌릴 수도 없었습니다.

즉.

PM> update-database -TargetMigration $InitialDatabase
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Reverting migrations: [201406020449030_initial].
Reverting automatic migration: 201406020449030_initial.
Automatic migration was not applied because it would result in data loss.
PM> update-database -TargetMigration $InitialDatabase -force
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Reverting migrations: [201406020449030_initial].
Reverting automatic migration: 201406020449030_initial.
System.Data.SqlClient.SqlException (0x80131904): Could not drop object 'dbo.UserProfiles' because it is referenced by a FOREIGN KEY constraint.

시도 2: 또한 마이그레이션을 추가할 때 -IgnoreChanges 플래그를 사용해 보았습니다.ASP.NET SimpleMembershipProvider에 대한 자동 마이그레이션

PM> Add-migration initial -IgnoreChanges
Re-scaffolding migration 'initial'.

PM> update-database -verbose

다시 한 번, update-database가 성공했지만 데이터베이스 열 DropboxUrl이 Designs 테이블에 추가되지 않은 동일한 현상을 확인했습니다.그러나 새 데이터베이스를 생성하면 DropboxUrl 열이 예상대로 나타납니다.

질문: 데이터베이스 업데이트를 수행하는 동안 데이터베이스 오류에 이미 '회사'라는 개체가 있는데도 여전히 내 열을 성공적으로 추가하는 문제를 해결하려면 어떻게 해야 합니까?그냥 작동하는 기본 시나리오 여야 할 것 같습니다.

감사해요.

도움이 되었습니까?

해결책

마이그레이션에서 Up() 및 Down() 메서드를 주석 처리할 때 데이터베이스 열을 추가하는 코드를 제거했습니다.

초기 항목에 대해 Up() 및 Down()을 다음과 같이 변경해야 합니다.

public override void Up() {
   AddColumn("Companies", "DropboxUrl", x => x.String());
}

public override void Down() {
    DropColumn("Companies", "DropboxUrl");
}

나중에 Entity Framework가 이를 파악하려면 초기 마이그레이션을 수행하여 기존 테이블이 있음을 이해해야 합니다. 코드에 속성을 추가하기 전에.예를 들어 Add-Migration -force -ignore.

그런 다음 열을 추가하고 Add-Migration AddedDropboxUrlColumn, 그리고 새 마이그레이션에서 설명한 대로 Up() 및 Down() 메서드를 생성합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top