更新操作麻烦

时间:2012-04-12 23:19:49

标签: asp.net-mvc entity-framework

这是我的更新操作:

        public void etat(string id)
    {

            Models.J2VEntities entity = new Models.J2VEntities();

            Models.user model = (from p in entity.user
                                 where p.iduser == id
                                 select p).SingleOrDefault();

            model.IsActive = !(model.IsActive);
            entity.user.AddObject(model);
            entity.ObjectStateManager.ChangeObjectState(model, System.Data.EntityState.Modified);
            entity.SaveChanges();
            RedirectToAction("Index", "Admin");
    }

当我执行时,我收到了这个错误:

  

System.InvalidOperationException:ObjectStateManager中已存在具有相同键的对象。现有对象处于状态修改状态。如果在状态中添加对象,则可以将对象添加回ObjectStateManager。

在这一行:entity.user.AddObject(model);

2 个答案:

答案 0 :(得分:0)

请改为尝试:

public void etat(string id){
 using( var entity = new Models.J2VEntities()){
    Models.user model = (from p in entity.user
                             where p.iduser == id
                             select p).SingleOrDefault();
    model.IsActive = !(model.IsActive);
    entity.user.Attach(model);
    entity.Entry(model).State = EntityState.Modified;
    entity.SaveChanges();
 }
}

using将确保正确处理和关闭您的连接,以确保您没有内存泄漏或不需要的打开连接。

答案 1 :(得分:0)

以这种方式加入:

using (var entity = new Models.J2VEntities())
            {
                Models.user model = (from p in entity.user
                                     where p.iduser == id
                                     select p).SingleOrDefault();
                model.IsActive = !(model.IsActive);
                entity.user.ApplyCurrentValues(model);
                entity.SaveChanges();
            }