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

asp.net-mvc entity-framework

Question

A portion of the Client entity attributes are included in my form, and I also add a hidden field that contains the client ID. The GET Edit operation delivers the client object itself.

Now when I want to update an entity, I've only tried it so far without first loading the object from the database. Because POST Edit's client object already has all it needs. Just those attributes on the entity in the datastore should be updated, please.

After updating my program from version 3.5 to version 4.0 RC1, my code now reads as follows:

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

Calling ApplyCurrentValues() gives the following error: "In the ObjectContext, the existing object is in the Added state. Only when the present item is unaltered or modified may changes be made."

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

Accepted Answer

You just need to do the following if you're passing over your EntityKey Ids from your and only want to store your submitted values:

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

Popular Answer

Use TryUpdateModel() in the following manner.

 [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