Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary key violation on adding of relationship from many to many linked tables in MVC 3 entity framework

I've read through scores of questions on here that seem at first to have a similar problem but just don't seem quite the same. Massive apologies if this is answered somewhere but like I say I've read through loads and can't find an answer.

I'm using Entity Framework and MVC 3. I'm trying to add tags to products in my entity framework, which have a many to many relationship and a table linking them with simply the two keys in the link table, so EF condenses the Tags into a property of Product. Tables are set up like so:

Product: ProductID [int, primary key], Name, etc.

Tags: TagName [string, primary key]

ProductTags: ProductID, TagName

So to access ProductTags I can just use product.Tags

This is my code:

dbProduct.Tags.Clear();
foreach (var tag in productModel.Tags)
{
    Data.Tag dbTag = new Data.Tag();
    dbTag.TagName = tag;
    dbProduct.Tags.Add(dbTag);
}

dbProduct being a Product entity, and Data being the namespace. productModel.Tags is a List<string>

When I SaveChanges() I get the following exception:

"Violation of PRIMARY KEY constraint 'PK_Tags_1'. Cannot insert duplicate key in object 'dbo.Tags'.\r\nThe statement has been terminated."

So what's really getting me is: why is it trying to add anything to dbo.Tags? It seems to me this should simply add to ProductTags not Tags. I make no mention of tags elsewhere in this method and so at no point try to add anything directly into the Tags table. It feels like I may have something set up wrong in my EF but I can't think what and it was generated from the database.

Sorry again if this is blindingly obvious, I'm feeling pretty stupid. Any help very much appreciated.

like image 418
Smeats Avatar asked Nov 19 '11 00:11

Smeats


1 Answers

The problem is you are creating a new Tag object with an existing primary key. When SaveChanges() is called EF detects the changes of the entities its already tracking and new entities added. Since your new Tag object was not tracked by EF, it tries to insert it.

You need to explicitly tell EF that the created tag is an existing one. To do that you need to attach it.

dbProduct.Tags.Clear();
foreach (var tag in productModel.Tags)
{
    Data.Tag dbTag = new Data.Tag();
    dbTag.TagName = tag;

    db.TagSet.Attach(dbTag);

    dbProduct.Tags.Add(dbTag);
}

This code assumes that you are not attaching single tag multiple times and all tags are existing tags.

like image 162
Eranga Avatar answered Nov 15 '22 22:11

Eranga