How to update a User entity that is converted to application?

-1

Code:

    public int UpdateUser(User usr)
    {
        db.Users.Attach(usr.ToApplication());
        db.Entry(usr.ToApplication()).State = System.Data.Entity.EntityState.Modified;
        return db.SaveChanges();
    }
  

Error:   "Attaching an entity of type 'Project.Data.Entities.Application' failed because another entity of the same type already has 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 received database-generated key values In this case use the' Add 'method or the' Added '

    
asked by anonymous 23.06.2016 / 15:06

1 answer

0

The error is very clear. You are adding the same object to the context twice.

Here:

    db.Users.Attach(usr.ToApplication());

And here:

    db.Entry(usr.ToApplication()).State = System.Data.Entity.EntityState.Modified;

I do not know what it does .ToApplication() , but I suppose it converts one object to another. However, in a modification, avoid using db.Users.Attach() .

    
29.08.2016 / 16:27