在更新时忽略某些列 [英] Ignore certain columns on update

查看:146
本文介绍了在更新时忽略某些列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我有这样的东西:

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 ....)只有修改列,因为我正在进行列审核。

I want to pass to the DB SQL-query (UPDATE Movie ....) only modified columns because I'm doing a column audit.

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

The code works ok, but the problem is that in my "Movie" Entity I have a "FlagOldMovie" property and others 10 properties witch I'm not using its in this view because they will stay the same, but the entityframework put to that properties defaults values so the "ApplyCurrentValues" find changes and that properties are updated too.

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

A workaround is to pass my not changed properties to html hidden inputs, but its privated data.

任何想法?

推荐答案

我fina lly得到它,首先,解决方案只适用于.NET 4.5 +

I finally got it, first at all, the solution only works on .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);

With this code, the only data modified is witch you want, next what I did is to audit columns changed extending _db.SaveChanges() to _db.SaveChangesAudito(id);

这篇关于在更新时忽略某些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆