2

My code looks like this: (where "user" is the UserProfile instance passed back from the view after being edited)

UserProfile original = DBContext.UserProfiles.Where(x => x.UserId == user.UserId).FirstOrDefault();
if (original != null)
{
   original = user;
   DAL.DAL.Instance.TGIMobiledb.SaveChanges();
}

This code fires without error, but does not update the DB. After some research it seems I have to add the following line before calling SaveChanges()

DBContext.Entry(original).State = EntityState.Modified;

But that line of code causes this error:
"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

The changes saves to the db fine if I assign every field manually like this:

original.UserId = user.UserId;
original.FirstName = user.FirstName;
original.Surname = user.Surname;
original.UserName = user.UserName;

Obviously this is less than optimal, especially with the larger entities.

billinkc
  • 59,250
  • 9
  • 102
  • 159
Swifty
  • 1,422
  • 2
  • 18
  • 38
  • Here http://stackoverflow.com/questions/15336248/entity-framework-5-updating-a-record is a good discussion on scenarios of updating entities in EF5. – juhan_h Jul 30 '13 at 08:08

2 Answers2

1

Try:

DBContext.Entry(original).CurrentValues.SetValues(user);
haim770
  • 48,394
  • 7
  • 105
  • 133
0

I'm guessing you retrieve the user and check for null to see if you need to create or update it.

Instead, you can check the UserId field.

if (user.UserId == 0)
{
    DBContext.UserProfiles.Add(user);
}
else
{
    DBContext.UserProfiles.Attach(user);
    DBContext.Entry(user).State = EntityState.Modified;
}
user247702
  • 23,641
  • 15
  • 110
  • 157