How to update a User Entity that is converted into application?

Asked

Viewed 56 times

-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 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."

1 answer

0

The error is crystal 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 don’t know what it does .ToApplication(), but I suppose it converts one object into another. Anyway, in a modification, avoid using db.Users.Attach().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.