Asp.net mvc 如何在MVC中使用EF更新数据库中的记录?
我想更新数据库中的记录,但当前Asp.net mvc 如何在MVC中使用EF更新数据库中的记录?,asp.net-mvc,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 &am
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 });
}
}
您正在以错误的方式更新它。您首先需要从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();
您正在以错误的方式更新它。您首先需要从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();
是的,这是正确的方法。OPs方式将抛出更新冲突,除非我从Getdata
获取Id
,emp.Id=Getdata.Id代码>。但是在代码中,您使用了Getdata.Id=model.Id
其中model.Id
没有任何Id
。跳过更新Getdata.Id。它不应该更新,因为它是主键。Rest所有可以根据业务逻辑更新的值。我会在上面编辑我的代码是的,这是正确的方法。OPs方式将抛出更新冲突,除非我从Getdata
获取Id
,emp.Id=Getdata.Id代码>。但是在代码中,您使用了Getdata.Id=model.Id
其中model.Id
没有任何Id
。跳过更新Getdata.Id。它不应该更新,因为它是主键。Rest所有可以根据业务逻辑更新的值。我将在上面编辑我的代码