Why does Ef Core not save my data in the database?
I have four models that are saved in sql server with Ef-Core and these four are Order, Contact, Address and BillingInfo.
Each Order has Contact and BillingInfo.
Each Contact has an Address.
Each BillingInfo has an Andress, too.
The problem is whenever i try to save it in the database i receive an error like this:
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_WSOrderAddresses_WebshopBillingInfoPocos_WebshopBillingInfoPocoID\". The conflict occurred in database \"DatabaseService_Name\", table \"dbo.WebshopBillingInfoPocos\", column 'Id'.\r\nThe statement has been terminated."}
and this is my code:
11 Replies
if something is missing tell me
this strikes me as odd
you set order.Id to 0 in a loop. did you mean to reset
item.Id
?
but in general, there is a loooot of manual entity state editing here
is everything new and untracked, or are several of these things tracked?this actually worked with items (not the issue)! the issue is with Address Billing and Contact, everything is new and is added
if everything is new, you dont need to do the whole
Context.Entity(x)..
stuff
you can just Context.Add(order);
and thats ityeah i know but this is not the issue! The issue lies somewhere different?
the issue is that your model violates your constraints. I can't tell you why that is, as I don't know what data you have in your database
its probably trying to insert something that already has an ID
and that ID is taken
or actually , its trying to insert an row with a foreign key to an object that isnt saved yet
do you want to see my models?
?
I have nothing else to contribute here really
I'm fairly EF can handle the correct order of insertions if you just let it, instead of doing all the manual overriding of EFs internals
i tried what you recommend but still not worked
with Context.Add(order), the same error appears!
yes, because using EF wrong is not the cause of the error but you should fix that anyway
foreign key constraint violation means that you're trying to set an invalid relationship to another entity
specifically
FK_WSOrderAddresses_WebshopBillingInfoPocos_WebshopBillingInfoPocoID
what does your code currently look like?i fixed it by changing the references to the foreign key! thx