将 EF 迁移迁移到 EFCore



我当前的 .NET Framework 应用程序中有大约 40 次迁移。我正在将数据库及其所有存储库移植到 .NET 标准库中,因为新应用程序是用 .NET Core 编写的,这会导致存储库的双重实现,而在 .NET Core 应用程序中,我们必须使用 Dapper 来不与其他任何东西冲突。

因此,我可以轻松地将IdentityDbContext和所有其他相关内容移植到EntityFrameworkCore

但现在是迁移。我知道Microsoft有一个关于从数据库中检索模型和 DbContext 的文档。但是,这会创建一个包含所有配置的很长OnModelCreating方法。看起来这可以工作但是,如果我想进行任何新的更改,我必须在那里和新的迁移中进行更改,并确保没有冲突。 此外,我们当前的迁移具有手动调整功能,以确保它适用于新数据库或现有生产数据库。有些事情没有以这种方式处理。

我想要的是将现有的单个迁移文件迁移到新的代码语法。我不在乎是否省略了手动调整,而是是否以某种方式自动转换了最大的东西。

例如:

.NET Framework:

public override void Up()
{
CreateTable(
"dbo.AdditionalCosts",
c => new
{
additionalCostId = c.Int(nullable: false, identity: true),
shoppingCartId = c.Int(),
shoppingCartProductId = c.Int(),
orderId = c.Int(),
inclPrice = c.Decimal(nullable: false, precision: 18, scale: 3),
taxPrice = c.Decimal(nullable: false, precision: 18, scale: 3),
description = c.String(),
title = c.String(),
costType = c.Int(nullable: false),
})
.PrimaryKey(t => t.additionalCostId)
.ForeignKey("dbo.Orders", t => t.orderId)
.ForeignKey("dbo.ShoppingCartProducts", t => t.shoppingCartProductId)
.ForeignKey("dbo.ShoppingCarts", t => t.shoppingCartId)
.Index(t => t.shoppingCartId)
.Index(t => t.shoppingCartProductId)
.Index(t => t.orderId);
}

.NET Core:

有没有可用的转换工具?

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
"dbo.AdditionalCosts",
c => new
{
additionalCostId = c.Column<int>(nullable: false), //idnetity: true?
shoppingCartId = c.Column<int>(),
shoppingCartProductId = c.Column<int>(),
orderId = c.Column<int>(),
inclPrice = c.Column<decimal>(nullable: false), //precision: 18, scale: 3?
taxPrice = c.Column<decimal>(nullable: false), //precision: 18, scale: 3
description = c.Column<string>(),
title = c.Column<string>(),
costType = c.Column<int>(nullable: false),
}, constraints: table =>
{
table.PrimaryKey("PK_AdditionalCost", t => t.additionalCostId);//default naming of PK_? why not automated anymore! :(
//etc..
});
//.PrimaryKey(t => t.additionalCostId)
//.ForeignKey("dbo.Orders", t => t.orderId)
//.ForeignKey("dbo.ShoppingCartProducts", t => t.shoppingCartProductId)
//.ForeignKey("dbo.ShoppingCarts", t => t.shoppingCartId)
//.Index(t => t.shoppingCartId)
//.Index(t => t.shoppingCartProductId)
//.Index(t => t.orderId);
}

我最终有几个选择:

  1. 遍历每个表,获取正确的索引名称、列名称并自行创建迁移文件。
  2. 使用代码回到过去,并使用 EFCore 再次生成每个迁移。
  3. 使用当前代码生成一个迁移,并以某种方式尝试对齐当前数据库。
    • 问题:EFCore 以不同的方式生成索引和某些 FK 名称。

所以......最终我只是用当前代码生成了一个新的迁移,在Visual Studio中做了一个模式比较,以检查真正的差异,并在需要时对迁移进行调整。然后,在发布时将当前数据迁移到新数据库。我目前正在这样做,所以我可能会稍后调整这个答案。

最新更新