即使表未更改,AddColumn也已添加到迁移中

时间:2020-05-13 07:34:59

标签: entity-framework ef-core-3.1

我在EF Core 3项目中具有以下模型:

public class MemberModel
{
    [Key]
    public int Id { get; set; }

    [Required, MaxLength(255)]
    public string Name { get; set; }
    [Required, MaxLength(30)]
    public string Phone { get; set; }
    [Required, MaxLength(255)]
    public string Email { get; set; }
    [Required, Display(Name="Company")]
    public int CompanyId { get; set; }
    public bool isDeleted { get; set; }
}

CompanyId属性仅在3月才添加,并且已完成迁移,时间戳为20200226063529:

public partial class addedCompanyIdColumn : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<int>(
            name: "CompanyId",
            table: "Members",
            nullable: false,
            defaultValue: 0);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "CompanyId",
            table: "Members");
    }
}

在此期间,我修改了表以将[Required]属性添加到字段中,并且没有应用任何迁移。

今天,我添加了一个迁移以更新其他一些表,并且迁移代码中包含的代码可以更改Members表,添加CompanyId列并创建Companies表已经在那里:

        migrationBuilder.AlterColumn<string>(
            name: "Phone",
            table: "Members",
            maxLength: 30,
            nullable: false,
            oldClrType: typeof(string),
            oldType: "nvarchar(30)",
            oldMaxLength: 30,
            oldNullable: true);

        migrationBuilder.AlterColumn<string>(
            name: "Name",
            table: "Members",
            maxLength: 255,
            nullable: false,
            oldClrType: typeof(string),
            oldType: "nvarchar(255)",
            oldMaxLength: 255,
            oldNullable: true);

        migrationBuilder.AlterColumn<string>(
            name: "Email",
            table: "Members",
            maxLength: 255,
            nullable: false,
            oldClrType: typeof(string),
            oldType: "nvarchar(255)",
            oldMaxLength: 255,
            oldNullable: true);

        migrationBuilder.AddColumn<int>(
            name: "CompanyId",
            table: "Members",
            nullable: false,
            defaultValue: 0);

        migrationBuilder.CreateTable(
            name: "Companies",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Name = table.Column<string>(maxLength: 255, nullable: true),
                isDeleted = table.Column<bool>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Companies", x => x.Id);
            });

因此更新失败。我必须去数据库删除CompanyId列和Companies表才能继续。

可能是什么引起了这个问题,我应该注意什么以避免将来出现这种结果?

是否有对模型的任何更改(无论多么微不足道)的要求,在执行任何事务之前都应先进行数据库更新?

0 个答案:

没有答案