实体框架 - 如何保存子实体

时间:2010-06-13 17:51:19

标签: entity-framework-4

我正在使用.NET 4 EF并且正在尝试保存实体(发票)的子实体(InvoiceLogs)。在表单提交上,我有一个分离的发票对象,其中包含已传递给我的控制器操作的已修改的InvoiceLog实体的EntityCollection。然后我将发票附加到数据上下文并调用SaveChanges。问题是这只保存了Invoice,它不保存修改后的InvoiceLog实体。如果我尝试单独附加InvoiceLog实体,那么它会给我以下错误:

ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法使用相同的键跟踪多个对象。

如何在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.InvoiceID };
                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);
            }

谢谢, 贾斯汀

1 个答案:

答案 0 :(得分:2)

搞定了,我需要在隐藏字段中填充InvoiceLogID和InvoiceID,以便在EntityCollection中填充它们。