【问题标题】:Unable to update column in Entity framework无法更新实体框架中的列
【发布时间】:2014-04-15 10:25:08
【问题描述】:


我只想更新表中的一列。我必须将活动列的值更改为 false。我正在使用实体框架。以下是我尝试过的代码:

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

我正在调试代码。它到达db_context.SaveChanges(),然后抛出以下错误:

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.

这里有什么问题?

【问题讨论】:

  • 您的示例中的“播放”是什么?您在哪里使用“用户”对象?
  • 对不起。应该是用户不玩。我将编辑问题。

标签: c# .net database entity-framework


【解决方案1】:

我将假设 PlayerInfoes 是包含您的用户的实体集合,如果不更新您的问题,我将修改此答案...

如果您想更新现有实体,并且获得了一些信息来识别该实体(用户 ID 和站点 ID),那么您可以从您的集合中检索该实际实体,对其进行修改并保存变化。像这样:

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

【讨论】:

  • 工作就像一个魅力!谢谢一堆。我所做的唯一改变是我在第 3 行使用了这个:((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.ChangeObjectState(player, EntityState.Modified);
猜你喜欢
  • 1970-01-01
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多