简体   繁体   中英

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.

After my database update, I started to get odd " The INSERT statement conflicted with the FOREIGN KEY constraint " error messages. I notice the error with only one database table A when executing my unit tests in Visual Studio.

The scenario for my unit test is as follows:

  1. The database table A has multiple many-to-one relations to other tables
  2. The database table A has FK s, which point to the PK of other tables
  3. All the data rows are properly inserted and commited to other tables ( PK Guids are unique)
  4. When debugging with C#, all the database table A FK s Guid values are correctly been set for the C# context.TableA.Add(item) statement
  5. When debugging with the SQL Server Profiler, the created SQL INSERT statement has the correct Guid values for each FK in the statement

As the result, the INSERT statement gives the FOREIGN KEY constraint error message. 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.

Therefore, I think I might have something wrong with my SQL server, or the with the table A.

Here's some statistics of the Table A

  1. It has about 80 columns
  2. Each row is approximately 10 kB large
  3. The table is empty when performing the INSERT

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.

I have drawn a relationship from table A to the other table. The relationship had two keys connected as follows

Table A <--------------------------------> CustomerAddress

PK Guid

FK CustomerAddressGuid <-------> PK Guid

FK CustomerGuid <------------------> FK CustomerGuid

Now the DeZing for Databases tool ordered

FK CustomerGuid <------------------> FK CustomerGuid (FK relations first) and

FK CustomerAddressGuid <-------> PK Guid (PK relations as next)

So, even the values were correct, the INSERT failed, because the FK - FK relation was prior to PK - FK.

Unfortunately the DeZing tool did not resolve this scenario automatically, and the relationship order was not easily visible in the tool.

The solution was to re-arrange the linked attributes order in the tool ( PK attributes first ), and re-create the database creation script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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