更新时忽略某些列

本文关键字:更新 | 更新日期: 2023-09-27 18:29:47

你好,我有这样的东西:

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

这个例子取自MVC 3中使用实体框架使用数据模型优先方法编辑实体的正确方法?

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

代码工作正常,但问题是在我的"电影"实体中,我有一个"FlagOldMovie"属性和其他10个属性,我没有在这个视图中使用它,因为它们将保持不变,但放入该属性的实体框架默认值,因此"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();