[英]C#, SQL Server: The INSERT statement conflicted with the FOREIGN KEY constraint
I'm coding database access methods with C#, Entity Framework and SQL Server. 我正在使用C#,实体框架和SQL Server编码数据库访问方法。
After my database update, I started to get odd " The INSERT statement conflicted with the FOREIGN KEY constraint " error messages. 更新数据库后,我开始收到奇怪的“ INSERT语句与FOREIGN KEY约束冲突 ”错误消息。 I notice the error with only one database table A when executing my unit tests in Visual Studio.
在Visual Studio中执行单元测试时,我注意到只有一个数据库表A的错误。
The scenario for my unit test is as follows: 我的单元测试的场景如下:
As the result, the INSERT statement gives the FOREIGN KEY constraint error message. 结果, INSERT语句给出FOREIGN KEY约束错误消息。 The INSERT fails with every single FK in it, and the INSERT is successful only after I delete all the FK s from the Table A.
插入 每个FK时 INSERT都会失败,并且只有在我从表A中删除所有FK之后, INSERT才会成功。
Therefore, I think I might have something wrong with my SQL server, or the with the table A. 因此,我认为我的SQL Server或表A可能有问题。
Here's some statistics of the Table A 这是表A的一些统计数据
I would be most happy to receive any hints for progressing with this item! 我很高兴收到有关此项目进展的任何提示!
Thanks for your help. 谢谢你的帮助。 I think I found a solution for my problem.
我想我找到了解决问题的办法。
I am using DeZing for Databases tool for my database design, and creation of database creation scripts. 我正在使用DeZing for Databases工具进行数据库设计以及创建数据库创建脚本。
I have drawn a relationship from table A to the other table. 我已经从表A到另一个表绘制了一个关系。 The relationship had two keys connected as follows
该关系具有如下连接的两个键
Table A <--------------------------------> CustomerAddress 表A <--------------------------------> CustomerAddress
PK Guid PK引导
FK CustomerAddressGuid <-------> PK Guid FK CustomerAddressGuid <-------> PK Guid
FK CustomerGuid <------------------> FK CustomerGuid FK CustomerGuid <------------------> FK CustomerGuid
Now the DeZing for Databases tool ordered 现在订购了DeZing for Databases工具
FK CustomerGuid <------------------> FK CustomerGuid (FK relations first) and FK CustomerGuid <------------------> FK CustomerGuid (首先是FK关系)和
FK CustomerAddressGuid <-------> PK Guid (PK relations as next) FK CustomerAddressGuid <-------> PK Guid (下一个PK关系)
So, even the values were correct, the INSERT failed, because the FK - FK relation was prior to PK - FK. 因此,即使值正确,INSERT也失败,因为FK-FK关系早于PK-FK。
Unfortunately the DeZing tool did not resolve this scenario automatically, and the relationship order was not easily visible in the tool. 不幸的是,DeZing工具无法自动解决此情况,并且在该工具中不容易看到关系顺序。
The solution was to re-arrange the linked attributes order in the tool ( PK attributes first ), and re-create the database creation script. 解决方案是在工具中重新排列链接属性的顺序( 首先是PK属性 ),然后重新创建数据库创建脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.