Created
July 5, 2012 16:42
-
-
Save brendanmckenzie/3054735 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[HttpPost] | |
public ActionResult EditInvoice(Invoice invoice, string subaction) | |
{ | |
ViewBag.Section = "Portfolio"; | |
ViewBag.Page = "Invoices"; | |
if (!string.IsNullOrEmpty(subaction)) | |
{ | |
ModelState.Clear(); | |
if (subaction == "add-item") | |
{ | |
invoice.Items.Add(new InvoiceItem() { Id = Guid.NewGuid(), InvoiceId = invoice.Id }); | |
} | |
else if (subaction.StartsWith("delete-item")) | |
{ | |
var item = invoice.Items.Single(i => i.Id == Guid.Parse(subaction.Substring(12))); | |
invoice.Items.Remove(item); | |
} | |
PopulateClients(); | |
return View(invoice); | |
} | |
if (ModelState.IsValid) | |
{ | |
db.Entry(invoice).State = EntityState.Modified; | |
var dbvalues = db.Entry(invoice).GetDatabaseValues(); | |
var currentItems = db.InvoiceItems.Where(ii => ii.InvoiceId == invoice.Id).Select(ii => ii.Id).ToList(); | |
var deleted = currentItems.Where(i => !invoice.Items.Select(ii => ii.Id).Any(ii => ii == i)); | |
var added = invoice.Items.Where(i => !currentItems.Any(ii => ii == i.Id)); | |
//var modified = invoice.Items./*Except(deleted).*/Except(added); | |
foreach (var item in invoice.Items) | |
{ | |
db.Entry(item).State = EntityState.Modified; | |
} | |
foreach (var item in deleted) | |
{ | |
db.InvoiceItems.Remove(db.InvoiceItems.Single(ii => ii.Id == item)); | |
} | |
foreach (var item in added) | |
{ | |
db.Entry(item).State = EntityState.Added; | |
} | |
db.SaveChanges(); | |
return RedirectToAction("Invoices"); | |
} | |
PopulateClients(); | |
return View(invoice); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment