0

这是我的更新操作:

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

4

2 回答 2

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将确保您的连接被正确处理和关闭,以确保您没有内存泄漏或不需要的打开连接。

于 2012-04-12T23:24:07.600 回答
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();
            }
于 2012-04-13T22:17:36.547 回答