Entity Framework - How to save child entities
I'm using .NET 4 EF and am trying to save the child entities (InvoiceLogs) of an entity (Invoice). On form submit I have a detached invoice object that has an EntityCollection of modified InvoiceLog entities passed to my controller action. I then attach the invoice to the data context and call SaveChanges. The problem is that this only saves the Invoice, it doesn't save the modified InvoiceLog entities. If I try to attach the InvoiceLog entities separately then it gives me the following error:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
How do I save child entities in EF 4??
//POST: /Secure/Invoices/SaveHours/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveHours([Bind(Exclude = "InvoiceLogs")]Invoice invoice)
{
TryUpdateModel(invoice.InvoiceLogs, "InvoiceLogs");
invoice.UpdateDate = DateTime.Now;
invoice.DeveloperID = Developer.DeveloperID;
//attaching existing invoice.
DataContext.InvoiceData.Attach(invoice);
//attach invoice hours.
foreach (var log in invoice.InvoiceLogs)
{
DataContext.InvoiceData.AttachLog(log);
}
//save changes.
DataContext.SaveChanges();
//redirect to invoice list.
return RedirectToAction("Index");
}
public static void Attach(Invoice invoice)
{
var i = new Invoice { InvoiceID = invoice.Invoic开发者_StackOverflow中文版eID };
db.Invoices.Attach(i);
db.Invoices.ApplyCurrentValues(invoice);
}
public static void AttachLog(InvoiceLog log)
{
var i = new InvoiceLog { InvoiceLogID = log.InvoiceLogID };
db.InvoiceLogs.Attach(i);
db.InvoiceLogs.ApplyCurrentValues(log);
}
Thanks, Justin
Got it working, I needed to populate the InvoiceLogID and InvoiceID in hidden fields so they'd get populated in the EntityCollection.
精彩评论