c# - EF Core 5 在迁移中创建表两次

标签 c# entity-framework-core ef-core-5.0

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

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

migrationBuilder.AddColumn(...)

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

第一

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);
            });
    ...

正如您所看到的,它们是相同的,为什么会发生这种情况?

最佳答案

事实证明,由于某种原因,visual studio for mac 又对我开了个玩笑。以下行已添加到我的 csproj 文件中。

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

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

解决方案很简单,如果您看到这些行,请将其删除,并且一切都应该按预期工作。

关于c# - EF Core 5 在迁移中创建表两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65765138/

相关文章:

c# - Global.asax 找不到代码隐藏类

c# - 在 C# 中避免多个 if 语句

c# - Entity Framework 7 与 .Net 中的现有数据库 MVC 6

c# - 如何将外键从一个 View 传递到另一个 View ?

c# - 关于 EF Core 中的 "owned"类型

c# - 使用 AJAX 从列表返回属性

c# - MVC4 + async/await + 在 Action 完成前返回响应

entity-framework - 如何包含大量子实体?

entity-framework-core - 如何使用 Automapper 和 Entity Framework 仅映射更改的属性

c# - Entity Framework 在外键条件下产生左连接