简体   繁体   English

插入具有外键约束的冲突

[英]Insert conflict with foreign key constraint

I am building an API with OrmLite from ServiceStack . 我正在使用ServiceStack的 OrmLite构建API。


When populating it with test data I get the following error: 当用测试数据填充它时,出现以下错误:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Order_Customer_CustomerId". INSERT语句与FOREIGN KEY约束“ FK_Order_Customer_CustomerId”冲突。 The conflict occurred in database "C:\\USERS\\ALECTAYLOR\\SOCIALBOOTSTRAPAPI\\SRC\\SOCIALBOOTSTRAPAPI\\APP_DATA\\USERAUTH.MDF", table "dbo.Customer", column 'Id'. 在数据库“ C:\\ USERS \\ ALECTAYLOR \\ SOCIALBOOTSTRAPAPI \\ SRC \\ SOCIALBOOTSTRAPAPI \\ APP_DATA \\ USERAUTH.MDF”的表“ dbo.Customer”的“ Id”列中发生了冲突。 The statement has been terminated. 该语句已终止。

Code (lines 213-236 + CreateOrders function): http://pastebin.com/Njhz7sD2 代码(213-236行+ CreateOrders函数): http ://pastebin.com/Njhz7sD2

Profiler output: http://fiddle.jshell.net/cTen2/1/show/ 探查器输出: http : //fiddle.jshell.net/cTen2/1/show/


Thanks for any advice on how to rectify this issue. 感谢您提供有关解决此问题的建议。

FOREIGN KEY constraint generally means that you are trying to insert a value into a table that doesn't exist in the reference table. 通常,FOREIGN KEY约束意味着您试图将一个值插入到引用表中不存在的表中。 Take a look at MSDN article on Foreign Keys for more info about what they are and how they work. 参阅有关外键的MSDN文章,以获取有关它们是什么以及它们如何工作的更多信息。 You need to have a look at the actual structure of the data tables order and customer. 您需要查看订单和客户数据表的实际结构。

I would guess that you are inserting a customerId into the orders table that doesn't exist in the customers table. 我猜您正在将一个customerId插入到customers表中不存在的orders表中。

since this is the insert that's failing, the only logical explanation is that customer number 1 doesn't exist. 由于这是插入操作失败的原因,因此唯一合乎逻辑的解释是客户编号1不存在。 I saw that you insert 3 customers a few lines before. 我看到您在3行之前插入了3个客户。 Maybe the transaction was not committed between the moment the customers were inserted and the order is inserted. 可能在插入客户和插入订单之间没有提交交易。

INSERT INTO "Order" ("CustomerId", "ShopId", "ShippingAddress", "OrderDate", "RequiredDate", "ShippedDate", "Total") VALUES (1, 0, '{line1:440 Crescent St, line2:South Melbourne, postCode:7416, city:Melbourne, country:Australia}', '20120430 07:43:18.686', NULL, NULL, 0); 插入“订单”(“ CustomerId”,“ ShopId”,“ ShippingAddress”,“ OrderDate”,“ RequiredDate”,“ ShippedDate”,“ Total”)值(1、0,'{line1:440 Crescent St,line2:南墨尔本,邮编:7416,城市:墨尔本,国家/地区:澳大利亚}','20120430 07:43:18.686',NULL,NULL,0);

Try to commit the insert after you insert the clients and before you insert the orders 在插入客户之后并在插入订单之前尝试提交插入

Alright, got it to work. 好吧,让它工作。

Needed to set the ShopId of Order and orderId of the orderDetails List . 需要设置OrderShopIdorderDetails List orderId

http://pastebin.com/TbrW150T http://pastebin.com/TbrW150T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM