MVC3使用EF 4.1和EntityState.Modified [英] MVC3 with EF 4.1 and EntityState.Modified

查看:186
本文介绍了MVC3使用EF 4.1和EntityState.Modified的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新与MVC3对象

我有我可以修改模型,请参见下面的示例:

I have a model that I can modify, please see the sample below:

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

该模型具有未在视图中显示和不能被用户修改了其他领域,但是当我点击提交按钮未在该视图显示领域得到了设置为null。

The model has other fields that are not showing in the view and cannot be modified by the user, but when I click the submit button the fields that were not showing in the view got set to null.

我可以以某种方式让EF不知道修改某些字段?谢谢你。

Can I somehow let EF know not to modify certain fields? Thanks.

推荐答案

一般来说,最好不要直接绑定到实体对象,而不是创建一个编辑模型并绑定到。

Generally it is better not to bind to the entity object directly, rather create an edit model and bind to that.

毕竟..什么来阻止别人回发不希望这种做法改变了价值观?

After all.. whats to stop someone posting back values you don't want changed with this approach?

这里的主要问题是,MVC模式结合改变其在上下文中,因此该实体框架不知道哪些值已经改变(并因此应该被更新)前模型中的属性

The main problem here is the fact that mvc model binding changes the properties in the model before its in a context therefore the entity framework doesn't know which values have changed (and hence which should be updated)

您已经缓解了略有 db.Entry(三).STATE = EntityState.Modified; 但是,告诉整个记录已经更新了实体框架。

You've mitigated that slightly with db.Entry(c).State = EntityState.Modified; but that tells the entity framework that the whole record has been updated.

我通常会做到以下几点:

I would normally do the following:


  1. 绑定到一个具体模型此控制器首先

  2. 创建要更新的实体类的一个实例,设置相应的ID,并将其连接到上​​下文

  3. 更新的实体的属性是一样的,你要绑定(对象附加,因此实体框架是跟踪哪些列现在正在改变)
  4. 模型
  5. 的SaveChanges

第三步是有点乏味,因此考虑使用像 automapper 一个工具,使事情变得更容易。

Step 3 is a bit tedious therefore consider using a tool like automapper to make things easier

编辑:

    [HttpPost]
    public ActionResult Edit(Company c)
    {
        if (ModelState.IsValid)
        {
            Company dbCompayObjct = new Company { companyId = c.companyId };
            db.Company.Attach(dbCompayObjct);

            dbCompanyObjct.CompanyName = c.CompanyName;
            dbCompanyObjct.City = c.City;

            db.SaveChanges();

            return RedirectToAction("Index");
        } 
        return View(c);
    }

这篇关于MVC3使用EF 4.1和EntityState.Modified的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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