【问题标题】:EF Core 5 creates tables twice in migrationsEF Core 5 在迁移中创建了两次表
【发布时间】:2021-04-22 04:43:32
【问题描述】:

我已经创建了一个项目和一个迁移,但似乎迁移在添加新迁移时并不关心以前的迁移,也就是说,迁移文件只是尝试创建相同的表两次。

我创建了两个迁移,FirstSecond。改变的是我向Post 实体添加了一个字符串属性(此处未显示)。我的预期是这样的:

migrationBuilder.AddColumn(...)

但是我得到了一个Second 迁移,其中包含来自First 迁移的所有内容,但是在创建表Post 时,它添加了列。几乎就像它甚至不关心有一个 First 迁移,因此就像它的第一次迁移一样。

第一

public partial class First : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "AspNetRoles",
            columns: table => new
            {
                Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
                Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
                NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
                ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_AspNetRoles", x => x.Id);
            });
    ...

第二

public partial class Second : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "AspNetRoles",
            columns: table => new
            {
                Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
                Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
                NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
                ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_AspNetRoles", x => x.Id);
            });
    ...

如您所见,它们是相同的,为什么会这样?

【问题讨论】:

  • 嗯 - 在生成第二个之前,您是否应用 First migraton 到您的数据库?
  • @marc_s 是的,我做到了,获取迁移列表将第二个显示为(待定)。但为什么需要这样做?对我来说,它可以弄清楚自上次迁移以来发生了什么变化,而不是实际数据库中的变化。
  • @marc_s 我发现了问题,超级奇怪,但事后看来,为什么一切都表现得如此奇怪是有道理的。

标签: c# entity-framework-core entity-framework-core-5


【解决方案1】:

事实证明,由于某种原因,Visual Studio for Mac 再次对我耍了花招。以下行已添加到我的 csproj 文件中。

<Compile Remove="Migrations\MainDbContextModelSnapshot.cs" />
<Compile Remove="Migrations\20210102195131_Test1.Designer.cs" />
<Compile Remove="Migrations\20210102195131_Test1.cs" />

现在,为什么它尝试再次从头开始创建所有内容,因为没有快照,这一切都说得通了。无论如何,如果这个奇怪的事情发生在其他人身上,你可能想看看你的 csproj 文件。我无法解释为什么要添加这些。

如果您看到这些行,解决方案就是删除它们,并且一切都应该按预期工作。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2021-05-04
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多