sql-server - 在 MVC 中使用 Entity Framework Code First 更新现有数据库

标签 sql-server asp.net-mvc entity-framework ef-code-first updatemodel

在我的 MVC 应用程序中,我使用了 Entity Framework 6 并使用代码优先方法创建了数据库。一段时间后,我通过添加新列和删除一些列来更新其中一个实体类。为了将这些更改反射(reflect)到数据库中,我按照以下步骤操作:

  1. Deleted the migrations folder in the project.
  2. Deleted the __MigrationHistory table in the database.
  3. Then run the following command in the Package Manager Console:
    Enable-Migrations -EnableAutomaticMigrations -Force

  4. Add the following lines in configuration file:
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;

  5. Run:
    Add-Migration Initial

  6. And finally, run:
    Update-Database -Verbose

但是,我遇到错误“数据库中已存在名为 'xxx' 的对象。”

为了解决这个问题,我在第 5 步之后创建的初始文件中的 Up 方法中注释了代码。这可以防止错误,但数据库中没有任何更改(更新的实体表仍与以前一样)。 错误在哪里?预先感谢您的帮助。

这是我在migration.cs文件中注释的Up方法:

    public override void Up()
    {
        CreateTable(
            "dbo.City",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false),
                    RegionID = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Region", t => t.RegionID)
            .Index(t => t.RegionID);

        CreateTable(
            "dbo.Multiplier",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    Status = c.Int(nullable: false),
                    Term = c.Int(nullable: false),
                    CityID = c.Int(nullable: false),
                    WhoIsOnline = c.String(nullable: false),
                    UserId = c.String(nullable: false),
                    InstituteName = c.String(nullable: false),
                    InstituteStatusID = c.Int(nullable: false),
                    InstituteAccreditationDate = c.DateTime(nullable: false),
                    Address = c.String(nullable: false),
                    Phone = c.String(nullable: false),
                    Fax = c.String(),
                    Email = c.String(nullable: false),
                    EurodeskEmail = c.String(nullable: false),
                    WebSite = c.String(),
                    ContactName = c.String(nullable: false),
                    ContactSurname = c.String(nullable: false),
                    ContactJobTitle = c.String(),
                    ContactAssignmentDate = c.DateTime(),
                    ContactWorkingStart = c.String(),
                    ContactWorkingkEnd = c.String(),
                    ContactPhone = c.String(),
                    ContactMobile = c.String(nullable: false),
                    ContactEmail = c.String(nullable: false),
                    ContactCityID = c.Int(nullable: false),
                    LegalRepresentativeName = c.String(nullable: false),
                    LegalRepresentativeSurname = c.String(nullable: false),
                })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.City", t => t.CityID)
            .ForeignKey("dbo.InstituteStatus", t => t.InstituteStatusID)
            .Index(t => t.CityID)
            .Index(t => t.InstituteStatusID);

        CreateTable(
            "dbo.InstituteStatus",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false),
                })
            .PrimaryKey(t => t.ID);

        CreateTable(
            "dbo.TrainingParticipant",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    TrainingID = c.Int(nullable: false),
                    ParticipantID = c.Int(nullable: false),
                    Multiplier_ID = c.Int(),
                })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Participant", t => t.ParticipantID)
            .ForeignKey("dbo.Training", t => t.TrainingID)
            .ForeignKey("dbo.Multiplier", t => t.Multiplier_ID)
            .Index(t => t.TrainingID)
            .Index(t => t.ParticipantID)
            .Index(t => t.Multiplier_ID);

        CreateTable(
            "dbo.Participant",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false),
                    Surname = c.String(nullable: false),
                    MultiplierID = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.Multiplier", t => t.MultiplierID)
            .Index(t => t.MultiplierID);

        CreateTable(
            "dbo.Training",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false),
                    Date = c.DateTime(nullable: false),
                    CityID = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.City", t => t.CityID)
            .Index(t => t.CityID);

        CreateTable(
            "dbo.Region",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false),
                })
            .PrimaryKey(t => t.ID);

    }


这是migration.cs文件中的Down方法:

    public override void Down()
    {
        DropForeignKey("dbo.City", "RegionID", "dbo.Region");
        DropForeignKey("dbo.TrainingParticipant", "Multiplier_ID", "dbo.Multiplier");
        DropForeignKey("dbo.TrainingParticipant", "TrainingID", "dbo.Training");
        DropForeignKey("dbo.Training", "CityID", "dbo.City");
        DropForeignKey("dbo.TrainingParticipant", "ParticipantID", "dbo.Participant");
        DropForeignKey("dbo.Participant", "MultiplierID", "dbo.Multiplier");
        DropForeignKey("dbo.Multiplier", "InstituteStatusID", "dbo.InstituteStatus");
        DropForeignKey("dbo.Multiplier", "CityID", "dbo.City");
        DropIndex("dbo.Training", new[] { "CityID" });
        DropIndex("dbo.Participant", new[] { "MultiplierID" });
        DropIndex("dbo.TrainingParticipant", new[] { "Multiplier_ID" });
        DropIndex("dbo.TrainingParticipant", new[] { "ParticipantID" });
        DropIndex("dbo.TrainingParticipant", new[] { "TrainingID" });
        DropIndex("dbo.Multiplier", new[] { "InstituteStatusID" });
        DropIndex("dbo.Multiplier", new[] { "CityID" });
        DropIndex("dbo.City", new[] { "RegionID" });
        DropTable("dbo.Region");
        DropTable("dbo.Training");
        DropTable("dbo.Participant");
        DropTable("dbo.TrainingParticipant");
        DropTable("dbo.InstituteStatus");
        DropTable("dbo.Multiplier");
        DropTable("dbo.City");
    }

最佳答案

为什么要执行步骤 1-4?那就是你出错的地方。如果您有一个先前生成的数据库并且您只是对架构进行更改,那么只需生成迁移并应用它即可。通过执行步骤 1-4,您将有效地撤销 Entity Framework 对此数据库的了解,并最终以代码优先的方式使用现有数据库。此时,您要么必须手动更改架构,要么让 Entity Framework 将其破坏并重新开始。

就回到可以再次应用迁移的状态而言,您在生成迁移并清空 Up 方法方面走在正确的轨道上。但是,您需要根据应用程序的先前状态(即与当前数据库匹配的状态)执行此操作。否则, Entity Framework 将生成包含您的代码更改的创建表。因此要遵循的步骤是:

  1. 将代码恢复到开始修改 POCO 之前的状态。
  2. 生成迁移。
  3. 删除 Up 方法中的所有内容
  4. 使用 update-database 应用迁移
  5. 重新应用您对 POCO 所做的更改。
  6. 生成另一个迁移(这个迁移现在应该只有添加/更改列语句,而不是创建表)
  7. 应用迁移。

之后,您应该可以再次出发了。然后,下次更改代码时,只需按照步骤 5 和 6 进行操作即可。

关于sql-server - 在 MVC 中使用 Entity Framework Code First 更新现有数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547951/

相关文章:

asp.net-mvc - ASP.NET MVC - 本地化路线

c# - Entity Framework和MVC在业务层或数据访问层创建DbContext

c# - 使用 EF 迁移将列从一个表连同值一起移动到另一个表

c# - 查询选择最畅销的产品

c# - 如何使用 LINQ 在函数中定义返回类型?

mysql - 列数未知的 SQL 查询

sql - 表连接没有返回准确的结果;任何想法为什么?

SQL查询以获取已注册英语或乌尔都语类(class)但未同时注册的学生

sql-server - SQL Server : enable remote connections without SSMS

asp.net - IIS 6.0通配符映射基准?