使用迁移 Entity Framework Core 添加数据而不指定 id

Fri*_*x G 7 c# entity-framework-core .net-core

我想使用 EF 迁移在我的数据库中添加一些数据。事实是所有 Id 都是自动生成的。我找到了使用 EF Core 实现它的标准方法,如下所示

modelBuilder.Entity<TypeNote>()
    .HasData(
    new TypeNote { Id = 1, Name = "General" },
    new TypeNote { Id = 2, Name = "E-mail" },
    new TypeNote { Id = 3, Name = "Meeting" },
    new TypeNote { Id = 4, Name = "Reminder" },
    new TypeNote { Id = 5, Name = "Telephone" },
    new TypeNote { Id = 6, Name = "Visit" }
);
Run Code Online (Sandbox Code Playgroud)

我的问题是我不想指定Id,但似乎没有其他方法可以使用HasData方法。

你知道另一种使用迁移在数据库中添加数据的方法吗?

Fri*_*x G 12

我找到了一种在迁移过程中进行插入的方法:

        migrationBuilder.InsertData(
            table: "TypeNote",
            columns: new[] { "Name" },
            values: new object[,]
            {
                { "Test" },
                { "Test1" }
        });
Run Code Online (Sandbox Code Playgroud)

事实是我想在迁移中访问 dbContext。这是不可能的,因为数据库正在更新。

  • 有没有办法获取插入行的 ID 并在另一个“InsertData”方法中使用它? (4认同)

aar*_*t89 5

首先,我创建了一个空迁移,将其命名为PopulatingTableX. 然后我在方法中添加了这样的数据插入(EF 6)Up

migrationBuilder.InsertData("Status",
           columns: new[] { nameof(StatusEntity.Entity), nameof(StatusEntity.Name), nameof(StatusEntity.CreationDate), nameof(StatusEntity.IsActive) },
           values: new object[,] {
                   { "Branch", "Active", DateTime.UtcNow, true },
                   { "Branch", "Closed", DateTime.UtcNow, true },
                   { "Branch", "Openning", DateTime.UtcNow, true },
                   { "Branch", "Closing", DateTime.UtcNow, true }
           }
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助。