更新数据库中的数据列表

时间:2015-03-25 00:12:47

标签: c#

public ActionResult Event_History(int id = 0)
    {
        //set into false the active flag of the event
        Events_Info_tbl events = db.Events_Info_tbl.Find(id);
        events.is_active = false;
        db.Entry(events).State = EntityState.Modified;

        //set the category under this event into inactive
        List<Events_Category_tbl> category = new List<Events_Category_tbl>();
        category = db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList();          
        foreach(var i in category){
            Events_Category_tbl cat = new Events_Category_tbl();
            cat.is_active = false;
            db.Entry(cat).State = EntityState.Modified; 
        }

        db.SaveChanges();

        TempData["MessageAlert"] = "Event is save in history!";

        return RedirectToAction("Index");


    }

Iam计划设置为非活动状态所有类别都属于该特定事件,但是当我尝试运行此代码时,显示错误&#34; ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法使用相同的键跟踪多个对象。&#34;指向我的代码db.Entry(cat).State = EntityState.Modified;

的这一部分

3 个答案:

答案 0 :(得分:1)

     foreach(var i in category){
        Events_Category_tbl cat = new Events_Category_tbl();
        cat.is_active = false;
        db.Entry(cat).State = EntityState.Modified; 
    }

这部分没有任何意义。您不应该创建Events_Category_tbl的新实例。

你应该只是

    foreach(var i in category){
        i.is_active = false;
    }

答案 1 :(得分:0)

表中的类别可能会重复....请替换:

db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList()

db.Events_Category_tbl.Where(x=>x.events_info_id==id).Distinct().ToList()

那样你就会确保每件事都重复一次

答案 2 :(得分:0)

下面的代码尝试创建新对象并保存在DB中,并且所有新对象都具有相同的Id,这就是为什么会出现该错误:

Events_Category_tbl cat = new Events_Category_tbl();
cat.is_active = false;
db.Entry(cat).State = EntityState.Modified;

您无需创建新对象,只需更新检索到的实体:

public ActionResult Event_History(int id = 0)
{
    //set into false the active flag of the event
    var events = db.Events_Info_tbl.Find(id);
    events.is_active = false;        

    //set the category under this event into inactive
    var category = db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList();          
    foreach(var cat in category){
        cat.is_active = false;
    }

    db.SaveChanges();

    TempData["MessageAlert"] = "Event is save in history!";

    return RedirectToAction("Index");


}