Cannot add an entity with a key that is already in use (LINQ)

后端 未结 4 747
一向
一向 2020-12-22 04:36

I get this error Cannot add an entity with a key that is already in use. when I run the code below.

Tables:

相关标签:
4条回答
  • 2020-12-22 05:05

    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
    
    0 讨论(0)
  • 2020-12-22 05:10

    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

    0 讨论(0)
  • 2020-12-22 05:16

    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.

    0 讨论(0)
  • 2020-12-22 05:20

    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

    0 讨论(0)
提交回复
热议问题