Why I do I fall into all of the hurdles for a simple update in EF? Why I do I fall into all of the hurdles for a simple update in EF? asp.net asp.net

Why I do I fall into all of the hurdles for a simple update in EF?


I only create once per request, once created I store it inside HttpContext.Items. Hence even though I make multiple request to DB, it uses same DbContext. Does that help?

If any of that "multiple requests to DB" loads user with the same ID you will get this exception. Try to use this:

public void Foo(int id, string name) {   var user = Db.Users.Local.SingleOrDefault(u => u.Id == id);   if (user == null) {      user = new User { Id = id };      Db.Users.Attach(user);   }    user.Name = name;   Db.SaveChanges();}

The code first try to get user instance from already loaded entities (no query to database) and creates a new instance only if the user was not loaded yet.