Rafa Ayadi
Rafa Ayadi

Reputation: 347

Attaching an entity of type 'ModelName" failed because another entity of the same type already has the same primary key value

I am using Entity to update a row in my database. My form return an Object that is supposed to update the old object that is stored in the DB. When I find out that the user left the password field blank, I want to keep the same old password value of the old object. Whenever I call the database asking for the old object, I hit the error when updating the object with Entity. I've tried all the AddOrUpdate, Attach, Detach stuff from Entity but nothing worked. Also, I can't do Delete then Add because the OldConnector has an incremental Id on the table that I can't modify. Here's my code :

public void Update(Connector NewConnector)
    {
        {
            if (NewConnector.Password == "")
            {
                Connector OldConnector = _db.ConnectorsTable.Where(x => x.ID == NewConnector.ID).FirstOrDefault(); //Grabbing the old connectors password
                NewConnector.Password = OldConnector.Password;
            }
        }
        _db.Entry(NewConnector).State = EntityState.Modified; //Code Crashes here
        _db.SaveChanges();
    }

Upvotes: 1

Views: 173

Answers (1)

DavidG
DavidG

Reputation: 119206

Entity Framework tracks objects you have loaded. So when you query the database for the OldConnector object, that item is kept in memory.

You then go on to try and save your NewConnector object which has the same primary key ID. Entity Framework checks it's internal state and finds a matching entity, that is why you get the error. Since you are trying to update the existing object, you should do this instead:

public void Update(Connector newConnector)
{
    if (newConnector == null)
    {
        throw new ArgumentNullException(nameof(newConnector));
    }

    var oldConnector = _db.ConnectorsTable
        .Where(x => x.ID == newConnector.ID)
        .Single(); //Grabbing the old connectors password

    if (newConnector.Password == "")
    {
        newConnector.Password = oldConnector.Password;
    }

    //Update the old entity with values from the new entity:
    _db.Entry(oldConnector).CurrentValues.SetValues(newConnector);
    _db.SaveChanges();
}

Upvotes: 1

Related Questions