MVC 2 EF 4.0正确处理产品类似内容的方法

时间:2016-06-10 13:16:49

标签: asp.net-mvc-2 entity-framework-4 edit

我星期一参加考试,我想问你是否有人知道在ProductView中处理编辑的最佳方法是什么。 或多或少是关于ProductController中的代码。

也许有人知道比我的两个尝试更清洁的解决方案。

这是我做的第一种方式:

我在编辑

中得到了这个
public ActionResult Edit(int id)
    {
        var productToEdit = (from p in db.Products
                             where p.ProductId == id
                             select p).First();

        return View(productToEdit);

    }

这在编辑的帖子中:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Product productToEdit)
    {
        try
        {
            // TODO: Add update logic here
            var originalProducts = (from p in db.Products
                                    where p.ProductId == productToEdit.ProductId
                                    select p).First();

            db.ApplyCurrentValues(originalProducts.EntityKey.EntitySetName, productToEdit);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        catch
        {
            return View();
        }
    }

这是一个很好的清洁解决方案吗?

这是我想到的第二个解决方案:

enter image description here

考试必须在MVC 2中使用EF 4.0进行。

2 个答案:

答案 0 :(得分:2)

你应该从不做一个全面的try阻止。您可能会吞下各种不同的异常,与数据库中不存在该对象的事实无关。

但是,你真的不应该使用try块。您只关注一个用例:未在数据库中找到匹配项,因此最好使用FirstOrDefault代替First然后覆盖null - 值场景:

public ActionResult Edit(int id, Product productToEdit)
{
    var originalProduct = db.Products.FirstOrDefault(p.ProductId == id);
    if (originalProduct == null)
    {
        return new HttpNotFoundResult();
    }

    // do update

    return View(productToEdit);
}

还要注意一些事项:

  1. 仍应传递id参数。它是URL的一部分,您应该使用它而不是发布的内容来查找正确的产品。发布的值可能会被修改,但您无法在不请求完全不同的资源的情况下更改网址中的id参数。

  2. 在后期操作上返回视图时,您需要传递已发布的模型。您在此处返回视图的唯一情况是,如果存在验证错误,除非您通过发布的模型,否则用户将无法更新现有值以修复这些错误。相反,他们只需要完全重新开始。

  3. 我在这里使用Entity Framework查询语法。虽然可以使用LINQ to SQL语法,但它更冗长,更不易阅读和非标准。

  4. 我使用FirstOrDefault而不是First进行演示,但在这里使用db.Products.Find(id)实际上最有意义。

答案 1 :(得分:0)

public ActionResult Get(int id)//将方法名称更改为get     {         var productToEdit =(来自db.Products中的p                              其中p.ProductId == id                              select p).FirstOrDefault(); //总是使用firstordefault而不是first

    return View(productToEdit);

}

使用第二种方法。