开发者

Saving changes in EF

I have a Quiz.Component.Product.Type and a view that provides the component. when the Create postback is called, because the view contains a Component_Id field, the model binder creates a Quiz.Component for me and sets the .Id to the correct value; all the other fields remain null and therefore so does Product, which means that when I .Add() and try to .SaveChanges() it complains that components participate in a relationship (with products) and that a product is expected.

this means I have to d开发者_StackOverflowo:

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

this might be asking too much but, is there a way I can have EF do those lookups for me?


It's asking too much. That's one strategy that could be used. In the POST action fetch the corresponding model using the id and then TryUpdateModel on it to update properties and finally invoke SaveChanges.

This is a commonly used paradigm:

[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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜