Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hi,

I have two tables one is product and second is tags. They have their respective columns. There is one to many relationship between product and tags. One product can have multiple tags(This has to be done using Database, no Javascript). So, I have included Product key as foreign key into tags table. I am able to create Model structure in Entity framework using code first approach.

Issue: There are two fields form for including tags from user. One is Product version and other is name of the tag. Where as tags' model contain ID(Database generated), Version, Name, Collection of product object and productID as foreign key.

When I receive data from form to controller it stuck at db.SaveChanges(). I says
The INSERT statement conflicted with the FOREIGN KEY constraint

How can I manage to include Foreign keys into tags object so that EF will save change?

What I have tried:

What I am thinking is to get the product id separately and then include it into tags object which will then add into context object for saving changes, but this is long shot. Is there is better way to do this?
Posted
Updated 7-Feb-17 21:51pm

1 solution

It sounds like you actually have a many to many relationship. This requires a link table which contains a foreign key for both products and tags. Each product can be inserted without constraint and each 'new' tag can be inserted without constraint. when you know which tags should be hooked up to which product then you insert a new relationship into the link table.

If that is not the case then you will have to insert each product before you can insert the tags.

I hope that helps. If I've missed something then let me know ^_^
Andy
 
Share this answer
 
Comments
Dishant Arora 8-Feb-17 4:42am    
I am sure I have build one to many relationship. There is no third joining table. Yes, Product will insert first and then tags related to product. There is the problem, product has already been added and when user add new tag then how will I make one to many relation. Upon form submit, the model doesn't contain foreign key. I am missing something here?
Andy Lanng 8-Feb-17 4:46am    
"I am missing something here" me too...
So the tags table has a column for productid. This is the foreign key. The product id must exist in the products table.
You insert a product, get the inserted product id and include that in the tags to insert.
If you follow those steps then you will not get the error. What are you missing?
Maybe post your code?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900