排除属性在实体框架更新 [英] Exclude Property on Update in Entity Framework

查看:112
本文介绍了排除属性在实体框架更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找,以纪念性质的正确方法不更新在MVC模型时被改变。

I've been looking for a proper way to mark a property to NOT be changed when updating a model in MVC.

例如,让我们这个小模型:

For example, let's take this small model:

class Model
{
    [Key]
    public Guid Id {get; set;}
    public Guid Token {get; set;}

    //... lots of properties here ...
}

然后在编辑方法MVC创建看起来是这样的:

then the edit method MVC creates looks like this:

[HttpPost]
public ActionResult Edit(Model model)
{
    if (ModelState.IsValid)
    {
        db.Entry(model).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(model);
}

现在,如果我的视图不包含令牌,将通过修改无效。

now if my View does not contain the Token, it will be nullified through that edit.

我在寻找这样的事情:

db.Entry(model).State = EntityState.Modified;
db.Entry(model).Property(x => x.Token).State = PropertyState.Unmodified;
db.SaveChanges();

到目前为止,我发现最好的办法是能够包容并设置我想包括手的所有属性,但我真的只想说要排除哪些。

The best way so far I found is to be inclusive and set all properties I want included by hand, but I really only want to say which ones to be excluded.

推荐答案

我们可以使用这样

 db.Entry(model).State = EntityState.Modified;
 db.Entry(model).Property(x => x.Token).IsModified = false;
 db.SaveChanges();

将更新,但没有令牌属性。

it will update but without Token property

这篇关于排除属性在实体框架更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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