I get this error Cannot add an entity with a key that is already in use.
when I run the code below.
Tables:
It looks like you're trying to add an object, while another one with same primary key exists. Are PageID
or CMSObjectID
primary keys? Or CMSAttributeID
?
You might also want to share more data about how your data tables look like.
Update: after you added database struct, I would look closer at this line:
newPoav.CMSPageObjectID = newPageObject.ID;
the newPageObject.ID
is probably not known at this time, because you didn't add the object to the DB yet (I suspect ID
is identity). I think you could use:
newPoav.CMSPageObject = newPageObject
you have to add some code just for testing if the list newPoavs
have a key exist already in the database
you can just add this
foreach (CMSPageObjectAttributeValue poav in originalPoavs)
{
CMSPageObjectAttributeValue newPoav = new CMSPageObjectAttributeValue();
newPoav.CMSAttributeID = poav.CMSAttributeID;
newPoav.CMSPageObjectID = newPageObject.ID;
newPoav.LCID = poav.LCID;
newPoav.Value = poav.Value;
newPoavs.Add(newPoav);
if(_db.CMSPageObjectAttributeValues.Any(x=>x.LCID == newPoav.LCID & x.CMSAttributeID == newPoav.CMSAttributeID & x.CMSPageObjectID == newPoav.CMSPageObjectID ))
MessageBox.Show("Already exist");
}
just to test your values
Seems you are missing primary key or an unique key on CMSPageObject table. Please try to verify the keys in the database. I had same issue since I had missed the PK on the table.
Cheers.
I was getting this error and it was because I had forgotten to set the Primary Key field in the database to "Identity Specification" (auto-increment). But that is just a guess