0


I want to update only one column in a table. I have to change value of active column to false. I'm using Entity framework. Following is the code that I tried for it:

public void DeleteUser(string userid, string siteid) { var user = new User(){UserId = userid, SiteId= siteid, Active = false}; //Changing Active to false, orignially true db_context.Users.Attach(user); db_context.Configuration.ValidateOnSaveEnabled = false; db_context.Entry(user).Property(x => x.Active).IsModified = true; db_context.SaveChanges(); db_context.Configuration.ValidateOnSaveEnabled = true; } 

I'm debugging the code. It reaches db_context.SaveChanges() and then throws following error:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries. 

What's wrong here?

2
  • What is 'play' in your example? And where are you using the 'user' object? Commented Apr 15, 2014 at 11:46
  • I'm sorry. It should be user not play. I'll edit the question. Commented Apr 15, 2014 at 11:47

1 Answer 1

1

I am going to assume that PlayerInfoes is your entity collection that contains your users, if not update your question and I'll amend this answer ...

If you want to update an existing entity, and you are given a couple of pieces of info to identify that entity (the userid and siteid), then you can retrieve that actual entity from your collection, modify it, and save the changes. Like this:

public void DeleteUser(string userid, string siteid) { var user = db_context.PlayerInfoes.Where(x=>x.UserId.Equals(userid) && x.SiteId.Equals(siteid); user.Active = false; db_context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified); db_context.SaveChanges(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm! Thanks a bunch. Only change I did was I used this: ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.ChangeObjectState(player, EntityState.Modified); instead, in line 3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.