更新时忽略某些列

你好我有这样的事情:

public ActionResult Edit(int id) { var movie = (from m in _db.Movies where m.Id == id select m).First(); return View(movie); } [HttpPost] public ActionResult Edit(Movie movie) { try { var originalMovie = (from m in _db.Movies where m.Id == movie.Id select m).First(); _db.Movies.ApplyCurrentValues(movie); _db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } 

这个例子是从正确的方式采用数据模型优先方法使用entity framework编辑MVC 3中的实体?

我想传递给DB SQL查询(UPDATE Movie ….)只修改了列,因为我正在进行列审计。

代码工作正常,但问题是,在我的“电影”实体中,我有一个“FlagOldMovie”属性和其他10个属性,我在这个视图中没有使用它,因为它们将保持不变,但entity framework付诸实践属性默认值,因此“ApplyCurrentValues”找到更改,并且属性也会更新。

解决方法是将我未更改的属性传递给html隐藏输入,但是它的私有数据。

任何的想法?

 [HttpPost] public ActionResult Edit([Bind(Exclude ="column_name")] Movie movie) { //code here } 

这会忽略您指定的列,我通常会这样做以排除像Id这样的字段。

但是,如果您忽略了许多列,那么您应该考虑ViewModel概念,其中您只拥有视图所需的属性。

编辑:还有一些问题吗?

以下是添加多个的方法

 [HttpPost] public ActionResult Edit([Bind(Exclude ="c_name, c_name2, c_name3")] Movie movie) { //code here } 

您可以告诉EF您要更新哪些字段。 尝试这样的事情:

 _db.Movies.Attach(movie); ObjectStateEntry entryToUpdate = db.ObjectStateManager.GetObjectStateEntry(movie); entryToUpdate.SetModifiedProperty("field1"); // Replace "field1" with the name of the 1st field to update entryToUpdate.SetModifiedProperty("field2"); // Replace "field2" with the name of the 2nd field to update entryToUpdate.SetModifiedProperty("field3"); // Replace "field3" with the name of the 3rd field to update _db.SaveChanges(); 

最佳做法是使用ViewModel而不是域/数据模型传递给视图或从视图传递。 🙂

这种情况说明了不这样做的危险之一。

我终于明白了,首先,该解决方案仅适用于.NET 4.5+

 [HttpPost] public ActionResult Edit(Movie movie) { try { //Get DB version var originalMovie = (from m in _db.Movies where m.Id == movie.Id select m).First(); //Mark changes with data received _db.Movies.ApplyCurrentValues(movie); //CODE ADDED - Ignoring field/properties you dont want to update to DB ObjectStateEntry entryToUpdate = db.ObjectStateManager.GetObjectStateEntry(originalMovil); entryToUpdate.RejectPropertyChanges("field1"); entryToUpdate.RejectPropertyChanges("field2"); entryToUpdate.RejectPropertyChanges("field3"); //----------------- _db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } 

使用此代码,唯一修改的数据是你想要的,接下来我做的是审计列更改扩展_db.SaveChanges()到_db.SaveChangesAudito(id);

试试这样

 var originalMovie = (from m in _db.Movies where m.Id == movie.Id select m).First(); originalMovie.updateme = updating; _db.SaveChanges();