【问题标题】:Updating only part of a model仅更新模型的一部分
【发布时间】:2011-09-06 06:03:23
【问题描述】:

我首先使用 ASP.NET MVC 3 和实体框架代码。我有一个页面(使用 Razor View Engine),允许用户更新模型(产品)的一部分:

@Html.LabelFor(model => model.Overview) @Html.TextAreaFor(model => model.Overview)

@Html.LabelFor(model => model.Description)
@Html.TextAreaFor(model => model.Description)

@Html.HiddenFor(model => model.ProductId)

我的控制器方法如下所示:

[HttpPost]
public ActionResult Update(Product product)
{
  db.Products.Attach(product);
  db.SaveChanges();
}

我要做的就是更新 Product 模型的 Overview 和 Description 属性。但是,当我运行代码时,模型并没有在数据库中更新,我也没有收到任何错误。

当我在调试时检查产品对象时,我发现虽然 ProductId、Overview 和 Description 字段是正确的(根据 FORM POST),但其他字段是 NULL(我希望如此)。

我想知道产品对象的不完整状态是否导致它无法保存到数据库中?

这是模型:

公开课产品 { 公共 int ProductId { 获取;放; }

    [Required(ErrorMessage = "Please enter a description")]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }

    [DataType(DataType.MultilineText)]
    public string Overview { get; set; }

    public int SupplierId { get; set; }
    public virtual Supplier Supplier { get; set; }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    如果您知道要更新实体的哪些属性,则可以使用 EF 中的 ChangeTracker 仅将这些属性标记为已更改。以下是来自优秀书籍 [Programming Entity Framework: DbContext] (http://shop.oreilly.com/product/0636920022237.do) 的修改示例:

    db.Products.Attach(product);
    var entry = db.Entry(product);
    entry.State = EntityState.Unchanged;
    entity.Property(p => p.Overview).IsModified = true;
    entity.Property(p => p.Description).IsModified = true;
    db.SaveChanges();
    

    这将为您节省往返数据库的时间。但当然,它只有在您知道哪些属性正在发生变化时才有效。还有其他一些方法可以实现这一点,但这是最直接的。

    【讨论】:

      【解决方案2】:

      在进行编辑时,请先尝试从数据库中选择一条现有记录(您要编辑的记录),然后使用从表单中收集的值(即传递给控制器​​操作的模型)对其进行更新,然后保存它。

      例如

      [HttpPost]
      public ActionResult Update(Product productPassedInFromView)
      { 
          Product productToEdit = db.Products.Find(productPassedInFromView.ID);
      
          productToEdit.Property1 = productPassedInFromView.Property1;
          productToEdit.Property2 = productPassedInFromView.Property2;
          //Continue for all the fields you want to edit.
      
          db.SaveChanges();
      }
      

      【讨论】:

        猜你喜欢
        • 2011-04-03
        • 2012-03-15
        • 2019-11-14
        • 2015-06-18
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        相关资源
        最近更新 更多