public async Task <IActionResult> Create(GroupCreateEditViewModel model) { if (!ModelState.IsValid) { var info = this.GetGroupInfo(model.GroupType); ViewData["GroupDescriptions"] = info.ToDictionary(i => i.Id, i => i.Description); return(View("CreateEdit", model)); } this.livestockDb.AdmuGroup.Add(model.Group); await this.livestockDb.SaveChangesAsync(); await this.AddToGroup(model.Group, model.SelectedMemberIds); return(RedirectToAction("Index")); }
public async Task <IActionResult> Edit(GroupCreateEditViewModel model) { if (!ModelState.IsValid) { var info = this.GetGroupInfo(model.GroupType); ViewData["GroupDescriptions"] = info.ToDictionary(i => i.Id, i => i.Description); return(View("CreateEdit", model)); } this.livestockDb.Update(model.Group); // First, remove any that no longer are needed. var maps = this.GetMappingInfo(model.Group); var ids = model.SelectedMemberIds.ToList(); // We need it as a list so we can use .Remove foreach (var id in maps.Select(m => m.DataId).ToList()) // We're removing things, so we need to cache the data in a list first. { if (!ids.Contains(id)) { if (model.Group.GroupType == AdmuGroupEntityTypes.Critter) { await this.data.MultiReference <Critter>().RemoveByIdAsync(model.Group, id); } else if (model.Group.GroupType == AdmuGroupEntityTypes.User) { await this.data.MultiReference <User>().RemoveByIdAsync(model.Group, id); } else { throw new InvalidOperationException(); } } // Remove the id from the list, since we either deleted it, or we're not changing it at all. ids.Remove(id); } // Finally, add in anything new. await this.AddToGroup(model.Group, ids); await this.livestockDb.SaveChangesAsync(); return(RedirectToAction("Index")); }