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

匆匆过客 提交于 2020-01-01 09:44:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8190985/primary-key-violation-on-adding-of-relationship-from-many-to-many-linked-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!