// TODO: Clean this up and use an algorithm that is scalable for child items public void Update(Notebook item) { try { SQLiteDatabaseContext context = database.Context; context.SaveChanges(); Notebook existingNotebook = context.Notebooks .Where(n => n.ID == item.ID) .Include(n => n.Stacks) .SingleOrDefault(); if (existingNotebook == null) { throw new Exception($"The notebook with ID { item.ID } could not be found"); } context.Entry(existingNotebook).CurrentValues.SetValues(item); // Delete children foreach (Stack existingStack in existingNotebook.Stacks) { if (!item.Stacks.Any(s => s.ID == existingStack.ID)) { context.Stacks.Remove(existingStack); } } // Update and insert children foreach (Stack stack in item.Stacks) { Stack existingStack = existingNotebook.Stacks .Where(s => s.ID == stack.ID && s.ID != default) .SingleOrDefault(); if (existingStack == null) { // Insert child existingNotebook.Stacks.Add(stack); } else { // Update child context.Entry(existingStack).CurrentValues.SetValues(stack); } UpdateStack(stack); } context.SaveChanges(); } catch (Exception e) { InformationDispatcher.Default.Dispatch(e); // TODO: Remove throw new DataSourceException("Could not update notebook", e); } }
private void UpdateStack(Stack item) { try { SQLiteDatabaseContext context = database.Context; Stack existingStack = context.Stacks .Where(s => s.ID == item.ID) .Include(s => s.Fields) .SingleOrDefault(); if (existingStack == null) { return; } context.Entry(existingStack).CurrentValues.SetValues(item); // Delete children foreach (CustomField existingField in existingStack.Fields) { if (!item.Fields.Any(f => f.ID == existingField.ID)) { context.Fields.Remove(existingField); } } // Update and insert children foreach (CustomField field in item.Fields) { CustomField existingField = existingStack.Fields .Where(f => f.ID == field.ID && f.ID != default) .SingleOrDefault(); if (existingField == null) { // Insert child existingStack.Fields.Add(field); } else { // Update child context.Entry(existingField).CurrentValues.SetValues(field); } } context.SaveChanges(); } catch (Exception e) { InformationDispatcher.Default.Dispatch(e); // TODO: Remove throw new DataSourceException("Could not update stack", e); } }