实体框架 - 在更新时保存子实体

时间:2010-07-10 19:24:39

标签: entity-framework entity-framework-4

我有一个Invoice实体,它有子InvoiceLog实体。当我第一次创建一个Invoice并添加其InvoiceLog实体并保存时,它工作正常。但是,如果我然后编辑发票并尝试添加其他InvoiceLog实体,它将完全忽略新的InvoiceLog实体,并且根本不保存它们。我有什么想法吗?

//POST: /Secure/Invoices/Save/
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(Invoice invoice)
        {
            invoice.UpdateDate = DateTime.Now;
            invoice.DeveloperID = Developer.DeveloperID;
            invoice.InvoiceStatusID = (int)Enums.InvoiceStatus.Open;
            if (invoice.InvoiceID == 0)
            {//inserting new invoice.
                DataContext.InvoiceData.Insert(invoice);
            }
            else
            {//attaching existing invoice.
                DataContext.InvoiceData.Attach(invoice);
            }
            AddHours(invoice);
            //save changes.
            DataContext.SaveChanges();
            //redirect to invoice list.
            return RedirectToAction("Index");
        }

        private void AddHours(Invoice invoice)
        {
            //get existing logs.
            IQueryable<InvoiceLog> existingLogs = null;
            if(invoice.InvoiceID > 0)
            {
                existingLogs = DataContext.InvoiceData.GetLogs(invoice.InvoiceID);
            }
            //create new logs.
            var numDays = invoice.EndDate.Subtract(invoice.StartDate).TotalDays;
            for (int k = 0; k <= numDays; k++)
            {
                //check if log already exists.
                var existingLog = existingLogs.ToList().FindIndex(l => l.LogDate == invoice.StartDate.AddDays(k));
                if (existingLog == -1)
                {
                    //add new log.
                    var log = new InvoiceLog();
                    log.CreateDate = DateTime.Now;
                    log.UpdateDate = DateTime.Now;
                    log.Hours = 0;
                    log.InvoiceID = invoice.InvoiceID;
                    log.LogDate = invoice.StartDate.AddDays(k);
                    invoice.InvoiceLogs.Add(log);
                }
            }
        }

谢谢, 贾斯汀

1 个答案:

答案 0 :(得分:0)

您可以在附加InvoiceLogs

之前尝试添加invoice
    else
    {//attaching existing invoice.
        AddHours(invoice);
        DataContext.InvoiceData.Attach(invoice);
    }