public static void Update(InvoiceModel invoiceModel) { Invoice entity = getEntityByModel(invoiceModel); string result = string.Empty; if (entity.IsValid()) { if (invoiceModel.Id > 0) { result = service.Update(entity); } else { result = service.Insert(entity); } if (!string.IsNullOrEmpty(result)) { var savedDetail = getInvoiceDetailByInvoiceId(result); if (savedDetail.Count() > invoiceModel.InvoiceDetail.Count()) { var tobeDeleted = savedDetail.Take(savedDetail.Count() - invoiceModel.InvoiceDetail.Count()); foreach (var item in tobeDeleted) { detailService.Delete(item.Id.ToString(), AuthenticationHelper.CompanyId.Value); } savedDetail = getInvoiceDetailByInvoiceId(result); } foreach (var detail in invoiceModel.InvoiceDetail) { InvoiceDetail detailEntity = getEntityByModel(detail); if (detailEntity.IsValid()) { detailEntity.InvoiceId = Convert.ToInt64(result); if (savedDetail.Count() > 0) { detailEntity.Id = savedDetail.FirstOrDefault().Id; savedDetail.Remove(savedDetail.FirstOrDefault(rec => rec.Id == detailEntity.Id)); detailService.Update(detailEntity); } else { detailService.Insert(detailEntity); } } } } } }