更新未反映在表格中

时间:2014-03-20 09:48:12

标签: c# asp.net linq asp.net-mvc-3 razor

这是我在Home控制器中定义的动作方法,用于更新行

[HttpPost]
public ActionResult UpdateISRCEntry(ABC.Models.tbl1 z, List<string> verticall,string Album, string Song)
{
    if (Session["user"] != null)
    {               
        if (verticall != null)
        {
            foreach (string s1 in verticall)
            {
                if (s1 == "Radio")
                { z.Radio = "Radio"; }
                if (s1 == "Online")
                { z.Online = "Online"; }
                if (s1 == "Mobile")
                { z.Mobile = "Mobile"; }
            }
        }

        tbl1.Service.Class1.updatetbl1(z, Album, Song);
        return RedirectToAction("Home");                
    }
    else
    {
        return RedirectToAction("Index");
    }
}

以下是我的方法已在class1中实现以实现可更新行

public static bool updatetbl1(tbl1 obj, string Album, string Song)
{
    ABC.Models.tbl1 objmain = new Models.mainISRC();

    using (ABCManagementDBEntities1 dbcontect = new ABCManagementDBEntities1())
    {
        var zz = (from z in dbcontect.tbl1 
                  where z.Album == Album && z.Song == Song select z
                 ).SingleOrDefault();
        objmain.Mood = obj.Mood;
        objmain.Online = obj.Online;
        objmain.Radio = obj.Radio;
        dbcontect.SaveChanges();
        return true;
    }
    return false;
}

所有这些代码都成功运行,但更新未反映在我的表格中。但是,在运行我的代码期间不会出现任何错误。请帮助别人。

2 个答案:

答案 0 :(得分:2)

dbcontect.SaveChanges();

之前添加此内容
dbcontect.Entry(objmain).State = EntityState.Modified;
dbcontect.SaveChanges();

或者我认为这样做

this.UpdateModel(objmain);
dbcontect.SaveChanges();

您应该在SaveChanges()

之前更新实体

答案 1 :(得分:1)

为什么要拉动zz对象而从不使用它?你写下你的&#34; updatetbl1&#34;的方式您正在向数据库插入新对象(objmain)而不是更新zz对象。我在这里假设是正确的吗?

我认为应该是这样的:

public static bool updatetbl1(tbl1 obj, string Album, string Song)
{
    ABC.Models.tbl1 objmain = new Models.mainISRC();

    using (ABCManagementDBEntities1 dbcontect = new ABCManagementDBEntities1())
    {
        var zz = (from z in dbcontect.tbl1 
              where z.Album == Album && z.Song == Song select z
             ).SingleOrDefault();
        zz.Mood = obj.Mood;
        zz.Online = obj.Online;
        zz.Radio = obj.Radio;
        dbcontect.Entry(zz).State = EntityState.Modified;
        dbcontect.SaveChanges();
        return true;
    }
    return false;
}