views:

21

answers:

1

Is it possible to use LINQ2SQL as MVC model and bind? - Since L2S "attachement" problems are really showstopping.

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

That does not work. :S

A: 

What does your Save View look like?

You can't just attach a new item to the EntitySet like that. -> Attaching requires a lot of checks and it is a real pain to implement. I tried it myself and didn't like it at all.

In your [HttpPost] method you'll need to update the model before you can save it:

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

It tries to update the model from the controllers valueprovider using they "Cart" prefix.

Shaharyar