代码之家  ›  专栏  ›  技术社区  ›  BuzzBubba

ASP.NET MVC LINQ-2-SQL作为模型-如何更新?

  •  0
  • BuzzBubba  · 技术社区  · 15 年前

    是否可以使用LINQ2SQL作为MVC模型并绑定因为L2S的“附件”问题真的很明显。

    [HttpPost]
      public ActionResult Save(ItemCart edCart)
      {
       using (DataContext DB = new DataContext())
       {
        DB.Carts.Attach(edCart);
        DB.Carts.Context.Refresh(RefreshMode.KeepChanges, edCart);
        DB.Carts.Context.SubmitChanges();
        DB.SubmitChanges();
       }
       return RedirectToAction("Index");
      }
    

    1 回复  |  直到 15 年前
        1
  •  0
  •   Faizan S.    15 年前

    保存视图是什么样子的?

    不能像那样将新项附加到EntitySet-&燃气轮机;连接需要很多检查,执行起来确实很痛苦。我自己试过,一点都不喜欢。

    在你的 [HttpPost]

    [HttpPost]
    public ActionResult Save(int id, ItemCart edCart) {
        DataContext DB = new DataContext(); // I'm doing this without a using keyword for cleanliness
        var originalCart = DB.Carts.SingleOrDefault(c => c.ID == id); // First you need to get the old database entry
    
            if (ModelState.IsValid & TryUpdateModel(edCart, "Cart")) { // This is where the magic happens.
                // Save New Instance
                DB.SubmitChanges.
    
                return RedirectToAction("Details", new { id = originalCart.ID });
            } else {
                // Invalid - redisplay with errors
                return View(edCart);
            }
        }
    

    它尝试使用“Cart”前缀从控制器valueprovider更新模型。