如何在MVC中使用EF更新数据库中的记录?

时间:2018-07-31 12:22:09

标签: asp.net-mvc

我想更新数据库中的记录,但是当前context.Entry(emp).State = System.Data.Entity.EntityState.Modified;没有执行。当控制权到达这一点时,它将移至catch块。

请告诉我我要去哪里哪里

[HttpPost]
public JsonResult _pEmp(EmpViewModel model)
{
    try
    {
        Emp emp = new Emp();

        if (model.File != null && model.File.ContentLength > 0)
        {
            string fileName = Path.GetFileName(model.File.FileName);
            string ImagePath = "/Image/" + fileName;
            string path = Path.Combine(Server.MapPath("~/Image/"), fileName);
            model.File.SaveAs(path);
            emp.FilePath = ImagePath;
        }

        var Getdata = context.emp.Where(x => x.Name == model.Name && x.Address == model.Address).FirstOrDefault();

        emp.Id = Getdata.Id;
        emp.Name = model.Name;
        emp.Address = model.Address;
        context.Entry(emp).State = System.Data.Entity.EntityState.Modified;
        context.SaveChanges();

        return Json(new { success = true, filePath = emp.FilePath });
    }
    catch
    {
        return Json(new { success = false });
    }
}

1 个答案:

答案 0 :(得分:2)

您正在错误地更新它。您首先需要从EF获取对象,更改其值然后保存。

这是更新后的代码-语法不符合要求,但可以为您提供思路。

var Getdata = context.emp.Where(x => x.Name == model.Name && x.Address == model.Address).FirstOrDefault();
            //Implement it like this 
            //Getdata.Id = model.Id; - Should not be updated since its primary key
            Getdata.Name = model.Name;
            Getdata.Address = model.Address;
            context.Entry(Getdata).State = System.Data.Entity.EntityState.Modified;
            context.SaveChanges();