Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an ID with me and I have name with me. So in essence, my method just has these parameters:

public void Foo(int id, string name)
{
}

and I have this piece of logic inside method:

User user = new User(){ Id = id, Name = name };
Db.Entry(user).State = System.Data.EntityState.Modified;
Db.SaveChanges();

That's it. Nothing fancy. I get this error: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"

and this answer by Ladislav Mrnka: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

suggests to use context.Entry(oldEntity).CurrentValues.SetValues(newEntity); but I don't really have oldEntity with me. Can anybody just please tell me how do I update just 1 property of User? I am getting nuts.

like image 728
Jack Avatar asked Aug 06 '12 16:08

Jack


1 Answers

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.

like image 158
Ladislav Mrnka Avatar answered Oct 05 '22 01:10

Ladislav Mrnka