【问题标题】:Saving changes in EF在 EF 中保存更改
【发布时间】:2011-08-29 01:56:30
【问题描述】:

我有一个Quiz.Component.Product.Type 和一个提供该组件的视图。当调用 Create postback 时,因为视图包含一个 Component_Id 字段,模型绑定器为我创建一个 Quiz.Component 并将 .Id 设置为正确的值;所有其他字段都保持为空,因此 Product 也是如此,这意味着当我 .Add() 并尝试 .SaveChanges() 时,它抱怨组件参与了关系(与产品)并且预期产品。

这意味着我必须这样做:

[HttpPost] ActionResult Create(Quiz q)
{
    q.Product = db.Components.Where(x => x.Id == q.Component.Id).Product;
    ...
}

这可能要求太多,但是有没有办法让 EF 为我进行这些查找?

【问题讨论】:

    标签: entity-framework asp.net-mvc-3 controller postback


    【解决方案1】:

    要求太多了。这是可以使用的一种策略。在 POST 操作中,使用 id 获取相应的模型,然后对其进行 TryUpdateModel 以更新属性并最终调用 SaveChanges。

    这是一个常用的范例:

    [HttpPost]
    public ActionResult Edit(int id)
    {
        var model = db.SomeModel.Single(x => x.ID == id);
        if (TryUpdateModel(model))
        {
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(model);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2021-03-25
      • 1970-01-01
      相关资源
      最近更新 更多