简体   繁体   中英

Unable to update column in Entity framework


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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM