Update an entity from an ASP.NET MVC page using the post to Edit action

asp.net-mvc entity-framework

Question

My form includes a subset of Client entity properties and I also include a hidden field that holds an ID of the client. The client entity itself is provided via the GET Edit action.

Now I want to do entity update but so far I've only been trying without first loading the entity from the DB. Because the client object that comes in POST Edit has everything it needs. I want to update just those properties on the entity in datastore.

I've ported my app from 3.5 to 4.0 RC1 and my code looks like this now:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Client client)
    {
        try
        {
            using (DocInvoiceEntities edmx = new DocInvoiceEntities())
            {
                if (string.IsNullOrEmpty(client.client_firstname))
                    ViewData.ModelState.AddModelError("client_firstname", "Firstname!");

                if (string.IsNullOrEmpty(client.client_lastname))
                    ViewData.ModelState.AddModelError("client_lastname", "Lastname!");

                // postcode
                client.PostCode = (from p in edmx.PostCodes where p.postcode.Equals(client.PostCode.postcode) select p).First();

                // check for errors
                if (!ViewData.ModelState.IsValid)
                    throw new InvalidOperationException();

                // save changes to datastore
                edmx.Clients.Attach(edmx.Clients.Single(c => c.client_id == client.client_id));
                edmx.Clients.ApplyCurrentValues(client);
                edmx.SaveChanges();

            }
            return RedirectToAction("Create", "Invoice");
        }
        catch
        {
            return View();
        }

ApplyCurrentValues() call throws this exception: "The existing object in the ObjectContext is in the Added state. Changes can only be applied when the existing object is in an unchanged or modified state."

1
1
3/15/2010 4:31:48 PM

Accepted Answer

If your sending over your EntityKey Ids from your and simply want to save your posted values then all you need is:

edmx.Clients.Attach(client);
edmx.SaveChanges();
1
3/15/2010 7:30:25 PM

Popular Answer

You can use TryUpdateModel() like so...

 [HttpPost]
    public ActionResult Edit(int id, FormCollection collection)
    {
        using (var context = new DocInvoiceEntities())
        {
            var client = context.Clients.Single(u => u.ID == id);

            if (TryUpdateModel(client))
            {
                context.SaveChanges();
                return RedirectToAction("Index");
            }
        }

        return View();
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow