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

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

问题描述

我一直在寻找一种正确的方法来标记在 MVC 中更新模型时不会更改的属性.

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

以这个小模型为例:

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.

我正在寻找这样的东西:

I'm looking for something like this:

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

它会更新但没有 Token 属性

it will update but without Token property

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

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