Error updating EF entity

4

Friends, the scenario is this: when I want to edit a record in my BD, I'm using context.Entry(entidad).State = EntityState.Modified; ; the problem arises that when you get to this line, you throw this exception to me

  

Attaching an entity of type 'MODEL' failed   because another entity of the same type has already the same primary   key value This can happen when using the Attach () method or setting   the state of an entity to 'Unchanged' or 'Modified' if any entities in   the graph have conflicting > key values. This may be because some   entities are new and have not yet received database-generated key   values. In this case use the 'Add' method or the 'Added' entity state   to track the graph and then set the state of non-new entities to   'Unchanged' or 'Modified' as appropriate.

Finding out about it, this makes reference to that in theory I have two entities in the memory of my context with the same PK (or is what I understood).

The update flow that I am applying is the following (roughly):

public bool Save(MiEntidad entity){
    if(entity.id > 0){
        context.Entry(entidad).State = EntityState.Modified;
    } else {
        db.add(entity);
    }
    return this.context.SaveChanges() > 0;
}

I tried getting the record that I want to update from my database and adding context.Entry(origin).State = EntityState.Detached; but the problem persists.

It is worth mentioning that if the entity is an update (entity.id> 0) I perform validations in which I assign ID to each child entity, but when doing this I use the parameter entity so I'm not using the context of my BD.

Any guidance would be appreciated!

    
asked by Paulo Urbano Rivera 03.10.2018 в 18:22
source

2 answers

1

Finally the solution found was to add the functionality of setting my entity with the new values and perform a " match " to the properties of the mentioned entity in the following way

public bool Save(MiEntidad entity){
    if(entity.id > 0){
        MiEntidad origin = context.MiEntidad.FirstOrDefault(x => x.id == entity.id);
        context.Entry(origin).CurrentValues.SetValues(entity);
    } else {
        db.Add(entity);
    }
    return this.context.SaveChanges() > 0;
}
    
answered by 03.10.2018 / 20:46
source
5

Just as your code is, a new entity would be created and you are only indicating that it will be modified by EntityState.Modified . What you need is to link to an existing entity using the Attach() method:

public bool Save(MiEntidad entity){
    if(entity.id > 0){
        conetxt.dbSet.Attach(entidad);
    } else {
        db.add(entity);
    }
    return this.context.SaveChanges() > 0;
}
    
answered by 03.10.2018 в 18:37