EF Core迁移现有数据

时间:2019-02-26 16:48:10

标签: c# entity-framework ef-core-2.1

我正在尝试在迁移过程中在Postgresql数据库中重新定位信息。一个表中存储的数据正通过一个通过外键将其链接的表分成多个表。

旧表:itemsInBag

ID
name
baglabel

新表格:item,itemsInBag,袋子

item
Id
Name

itemsInBag
Id
ItemId
BagId

bag
Id
BagLabel

当前,我有这些SQL语句尝试将它们链接在一起。这是在添加新表和字段之后以及在删除itemsInBag字段之前完成的。#

        migrationBuilder.Sql(
            "INSERT INTO items (Name)" +
            "SELECT (name) FROM itemsInBag");

        migrationBuilder.Sql(
            "INSERT INTO bag baglabel" +
            "SELECT DISTINCT baglabel FROM itemsInBag");

        migrationBuilder.Sql(
            "UPDATE itemsInBag SET bagid =(SELECT id FROM bag WHERE bag.baglabel = itemsInBag.baglabel)"
        );

        migrationBuilder.Sql(
            "UPDATE itemsInBag SET itemid =(SELECT id FROM items WHERE items.name = itemsInBag.name)"
        );

我在尝试运行迁移时收到此错误

$exception  {"23505: could not create unique index \"IX_itemsinbag_bagid_itemid\""} Npgsql.PostgresException

"Key (bagid, itemid)=(0, 0) is duplicated."

从我阅读的所有内容来看,这似乎是正确的方法。有更好的方法吗?有什么我想念的吗?

更新:如果我将对bagid和itemid的唯一约束移到SQL语句之后,则会收到此错误

$exception  {"23503: insert or update on table \"itemsinbag\" violates foreign key constraint \"FK_itemsinbag_bag_bagid\""} Npgsql.PostgresException
"Key (bagid)=(0) is not present in table \"bag\"

1 个答案:

答案 0 :(得分:0)

找出解决方案。安排索引和外键约束与我的SQL语句的位置有关。在重新排列表数据之后,需要创建外键约束。插入项上的项目表不存在之后,也发生错误。需要包含该架构,以便最终的SQL语句如下:

migrationBuilder.Sql(
        "INSERT INTO schema.items (Name)" +
        "SELECT name FROM schema.itemsInBag");

    migrationBuilder.Sql(
        "INSERT INTO schema.bag (baglabel)" +
        "SELECT DISTINCT baglabel FROM schema.itemsInBag");

    migrationBuilder.Sql(
        "UPDATE schema.itemsInBag SET bagid =(SELECT id FROM schema.bag WHERE schema.bag.baglabel = schema.itemsInBag.baglabel)"
    );

    migrationBuilder.Sql(
        "UPDATE schema.itemsInBag SET itemid =(SELECT id FROM schema.items WHERE schema.items.name = schema.itemsInBag.name)"
    );