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.