【发布时间】:2019-02-27 19:39:50
【问题描述】:
我正在尝试在迁移期间重新定位我的 postgresql 数据库中的信息。存储在一个表中的数据被分成多个表,其中一个表通过外键链接它们。
旧表:itemsInBag
ID
name
baglabel
新表:item、itemsInBag、bag
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\"
【问题讨论】:
-
旧表 itemsInBag 和新表 itemsInBag 的名称相同吗?你确定你想要吗?
-
旧表中的字段 {name,baglabel} 是否存在唯一约束?
-
如果表名引起问题,可以更改表名,这只是不符合命名约定的方式。旧的 itemsinbag 表没有唯一约束。在新的 bagid 和 itemid 中都必须是唯一的
标签: c# entity-framework ef-core-2.1