【问题标题】:Add-Migration not adding column to existing table in Entity Framework CoreAdd-Migration 未将列添加到 Entity Framework Core 中的现有表
【发布时间】:2017-09-29 14:33:08
【问题描述】:

我正在尝试向数据库中的现有表添加一个新列,我正在将新字段指定到类中并运行 Add-Migration 命令,但每次它使用 CreateTable 方法而不是 AddColumn 为整个表创建迁移类。下面是类和生成的迁移类代码。

public class UserSetup
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Age{ get; set; } // New Field Added

    }

但对于新字段,它正在为全表创建迁移类,如下所示:

public partial class AddUserSetup_1 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "UserSetup",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Name= table.Column<string>(nullable: false),
                    Age= table.Column<int>(nullable: false),
                 },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UserSetup", x => x.Id);
                });

       }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "UserSetup");
        }
    }

同样在 Add-Migration 中,它给了我以下错误,但即使是迁移类也正在创建中。

System.UnauthorizedAccessException:对路径“C:\Projects\PSM\Portal\src\Portal\Migrations\ApplicationDbContextModelSnapshot.cs”的访问被拒绝。

【问题讨论】:

    标签: entity-framework database-migration


    【解决方案1】:

    如果您使用的是 TFS,请务必签出以编辑您的“ApplicationDbContextModelSnapshot.cs”文件。它会工作得很好!

    【讨论】:

    • 谢谢丹尼尔。我很感激。
    【解决方案2】:

    评论您的新年龄字段

    //public bool Age{ get;放; } // 添加新字段

    打开“服务器资源管理器”窗口并确保您可以在“数据连接”中看到您的表

    在包管理器控制台中运行:

    1. 启用迁移
    2. 添加迁移 InitialCreate –IgnoreChanges
    3. 更新数据库

    现在 EF 应该可以识别您的数据库了 现在取消注释您的新“年龄”字段

    在包管理器控制台中运行:

    1. 添加迁移 AddUserSetup_1
    2. 更新数据库

    评论: 当您编写“Enable-Migrations”时,您可能需要像这样添加-Force:

    Enable-Migrations -Force

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2017-05-23
      • 1970-01-01
      • 2020-05-27
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多