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."