DbContext.SaveChanges() 没有更新数据库
DbContext.SaveChanges() is not updating the database
我正在尝试使用 entity framework 将实体保存到数据库中。我有处理对象更新的代码:
DbSet.Attach(entity);
之后我打电话给:
_context.SaveChanges();
(我在 MVC 中使用工作单元模式)
我要添加的实体具有状态 "Modified"。调用 SaveChanges 不会引发异常,但 return 值为 0 且数据库中的行未更新。知道为什么会这样吗?
P.S。我使用相同的上下文来检索实体,然后再保存它。
P.P.S 我可以 post 代码,但我不知道哪个代码是相关的,因为我不知道问题出在哪里。
我假设该实体已被附加为先前查询的结果,或者通过 Add
.
将其添加为新实体
当您通过 Attach
附加实体时,状态更改为未更改。
引用自this reference:
Note that entities that are already in the context in some other state will have their state set to Unchanged
由于对象已经在上下文中,您不必附加它。只需修改实体并调用 SaveChanges
.
试试这个
在控制器中
ObjEdbContext.Entry(qry).State = EntityState.Modified;
ObjEdbContext.SaveChanges();
ModelState.Clear();
在此代码中 qry
表示您更新的查询......
请试试这个,
Student stud = objContext.Students.Where(x => x.StudentId == model.StudentId).SingleOrDefault();
if (stud != null)
{
**objContext.Entry(stud).CurrentValues.SetValues(model);**
objContext.SaveChanges();
return RedirectToAction("Index");
}
return View(stud);
我从 http://www.c-sharpcorner.com/UploadFile/tirthacs/crud-operation-using-entity-framework-code-first/
得到这个例子
我正在尝试使用 entity framework 将实体保存到数据库中。我有处理对象更新的代码:
DbSet.Attach(entity);
之后我打电话给:
_context.SaveChanges();
(我在 MVC 中使用工作单元模式)
我要添加的实体具有状态 "Modified"。调用 SaveChanges 不会引发异常,但 return 值为 0 且数据库中的行未更新。知道为什么会这样吗?
P.S。我使用相同的上下文来检索实体,然后再保存它。
P.P.S 我可以 post 代码,但我不知道哪个代码是相关的,因为我不知道问题出在哪里。
我假设该实体已被附加为先前查询的结果,或者通过 Add
.
当您通过 Attach
附加实体时,状态更改为未更改。
引用自this reference:
Note that entities that are already in the context in some other state will have their state set to Unchanged
由于对象已经在上下文中,您不必附加它。只需修改实体并调用 SaveChanges
.
试试这个
在控制器中
ObjEdbContext.Entry(qry).State = EntityState.Modified;
ObjEdbContext.SaveChanges();
ModelState.Clear();
在此代码中 qry
表示您更新的查询......
请试试这个,
Student stud = objContext.Students.Where(x => x.StudentId == model.StudentId).SingleOrDefault();
if (stud != null)
{
**objContext.Entry(stud).CurrentValues.SetValues(model);**
objContext.SaveChanges();
return RedirectToAction("Index");
}
return View(stud);
我从 http://www.c-sharpcorner.com/UploadFile/tirthacs/crud-operation-using-entity-framework-code-first/
得到这个例子