MVC
MVC

Reputation: 679

How to update records in database using EF in MVC?

I want to update records in database but currently context.Entry(emp).State = System.Data.Entity.EntityState.Modified; is not executing. When control reach this point, it moves to catch block.

Please show me where I am going wrong.

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

Upvotes: 0

Views: 47

Answers (1)

Bill Berlington
Bill Berlington

Reputation: 2414

You are updating it wrong way. You first need to fetch the object from EF , change its values and then save it.

Here is the updated code - syntax not up to the mark, but will give you the idea.

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

Upvotes: 2

Related Questions