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

独自空忆成欢 提交于 2019-12-04 05:30:17

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.

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