本文介绍了如何使用Entity Framework和EntityState.Modified更新对象的每个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新给定实体对象的property1和property2以外的所有字段。

具有以下代码:

I need to update all fields except property1 and property2 for the given entity object.
Having this code:

    [HttpPost]
    public ActionResult Add(object obj)
    {
        if (ModelState.IsValid)
        {
                context.Entry(obj).State = System.Data.EntityState.Modified;

                context.SaveChanges();
         }
        return View(obj);
    }

如何更改它以向obj.property1和obj.property2添加一个异常因为没有使用此代码进行更新?

How to change it to add an exception to obj.property1 and obj.property2 for not being updated with this code?

推荐答案

我们假设您有一组要排除的属性:

Let's assume that you have a collection of the properties to be excluded:

var excluded = new[] { "property1", "property2" };

使用.NET 4.5上的EF5可以执行以下操作:

With EF5 on .NET 4.5 you can do this:

var entry = context.Entry(obj);
entry.State = EntityState.Modified;
foreach (var name in excluded)
{
    entry.Property(name).IsModified = false;
}

这使用.NET 4.5的新功能EF5,即使以前设置为修改,也可以将其设置为未修改。

This uses a new feature of EF5 on .NET 4.5 which allows a property to be set as not modified even after it has been previously set to modified.

在.NET 4上使用EF 4.3.1或EF5时,可以改为: p>

When using EF 4.3.1 or EF5 on .NET 4 you can do this instead:

var entry = context.Entry(obj);
foreach (var name in entry.CurrentValues.PropertyNames.Except(excluded))
{
    entry.Property(name).IsModified = true;
}

这篇关于如何使用Entity Framework和EntityState.Modified更新对象的每个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:01