Turn off tracking in entity framework model first

Viewed 20262

I'm tring to receive an entity and then update it, but I want to get it with no tracking, so I can attach it back to the context.

I have the EntityFramework.dll referenced (4.1). I generated the database from the model. (not code-first).

Get user:

db.Users.MergeOption = MergeOption.NoTracking;
IQueryable<User> query = db.Users;//.AsNoTracking(); //<-- apparently, this is code-first only.

return query;

Update user:

db.Users.Attach(user); //error here.
ObjectStateEntry entry = db.ObjectStateManager.GetObjectStateEntry(user);
entry.SetModifiedProperty(propertyName);
db.SaveChanges();
return user;

Error:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I call the method like this:

var user = userRepository.GetUsers().FirstOrDefault(u => u.UserId == userId);
user.Identifiers.Add(someIdent);
userRepository.UpdateUser(user);
2 Answers
Related