更新时忽略某些列

时间:2013-09-02 00:07:38

标签: c# asp.net-mvc entity-framework ef-database-first

你好我有这样的事情:

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

此示例取自Proper way to Edit an entity in MVC 3 with the Entity Framework using Data Model First approach?

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

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

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

有什么想法吗?

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以告诉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();

答案 2 :(得分:1)

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

这个场景说明了不这样做的危险之一。

答案 3 :(得分:0)

尝试那样

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

originalMovie.updateme = updating;

_db.SaveChanges();

答案 4 :(得分:0)

我终于明白了,首先,该解决方案仅适用于.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);

相关问题