【问题标题】:EF Core always create .Annotation("SqlServer:Identity", "1, 1") on add-migrationEF Core 总是在添加迁移时创建 .Annotation("SqlServer:Identity", "1, 1")
【发布时间】:2020-04-27 14:45:38
【问题描述】:

我遇到了迁移 EF Core 的问题。

为了使场景更清晰,我将其分配给现有数据库,该数据库旨在从现在开始使用迁移进行数据库控制。但我遇到了困难。

到目前为止我做了什么。

  1. 我从现有数据库生成了脚手架。

  2. 我添加了迁移,因此它为创建数据库生成了所有“Up”。

  3. 在干净的数据库中,运行 update-database。

到目前为止,一切都很完美,一切都按预期进行。但是从这一步开始,每次我生成一个新的迁移时,他(迁移)都坚持为所有表创建一个 Alter Column 语句。例如:

  migrationBuilder.AlterColumn<int>(
            name: "rac_n_codigo",
            table: "tb_rac_raca",
            nullable: false,
            oldClrType: typeof(int),
            oldType: "int")
            .Annotation("SqlServer:Identity", "1, 1");

创建表

  migrationBuilder.CreateTable(
            name: "tb_rac_raca",
            columns: table => new
            {
                rac_n_codigo = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                rac_c_nome = table.Column<string>(unicode: false, nullable: true),
                rac_d_alteracao = table.Column<DateTime>(type: "date", nullable: true),
                rac_c_usuario = table.Column<string>(unicode: false, nullable: true),
                rac_c_tipo = table.Column<string>(unicode: false, nullable: true),
                rac_d_modificacao = table.Column<DateTime>(type: "datetime", nullable: true),
                rac_c_unique = table.Column<Guid>(nullable: false, defaultValueSql: "(newid())"),
                rac_d_atualizado = table.Column<DateTime>(type: "datetime", nullable: false, defaultValueSql: "(getdate())"),
                rac_d_inclusao = table.Column<DateTime>(type: "datetime", nullable: false, defaultValueSql: "(getdate())")
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_tb_rac_raca", x => x.rac_n_codigo);
            });

【问题讨论】:

  • 看起来像一个错误。可以submit a new issue吗?
  • 我有一个非常相似的问题,你解决了吗?

标签: .net-core entity-framework-core entity-framework-migrations ef-core-2.2


【解决方案1】:

我使用 ValueGeneratedNever()

_ = builder.Property(x => x.Id).IsRequired().ValueGeneratedNever();

EF Core 5+ 在函数描述的元数据中是: 将属性配置为在保存此实体类型的实例时从不生成值。

【讨论】:

    【解决方案2】:

    假设您使用的是 Core 3.0 或 Core 3.1!

    添加包 Microsoft.EntityFrameworkCore.Relational

    此外,您可能需要在映射中明确指定标识列。

    builder.Property(o => o.Id).ValueGeneratedOnAdd().UseIdentityColumn();
    

    【讨论】:

    • 非常感谢,这种解决方案,因为不需要添加或映射,使用和测试解决方案,我需要将引用“Microsoft.EntityFrameworkCore.SqlServer”更新为 3.0 .1,连同安装“关系”之后完美运行,它开始生成迁移只有一致的变化。
    • @FelipeAntunes 是的,我注意到添加 Microsoft.EntityFrameworkCore.Relational 包就足够了。
    • 我需要一些帮助,同样的问题,但在 EF Core 5 中。点击链接的问题。
    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多