public async Task <NodeTag> RemoveTag(int tagId) { NodeTag tag = await _context.Tags .Include(t => t.Attachments) .Include(t => t.ProfilesFilterSelections) .SingleAsync(t => t.ID == tagId); _context.RemoveRange(tag.Attachments); _context.RemoveRange(tag.ProfilesFilterSelections); tag.Attachments = null; tag.ProfilesFilterSelections = null; _context.Remove(tag); await _context.SaveChangesAsync(); return(tag); }
private static async Task __SetProfileTagSelection( NtwkDBContext context, int profileId, IEnumerable <int> tagIDs, ProfileSelectedTagFlags flag ) { IEnumerable <int> ids = tagIDs as int[] ?? tagIDs.ToArray(); IEnumerable <ProfileSelectedTag> currentSelection = await context.ProfilesTagSelection .Where(pts => pts.BindedProfileID == profileId) .ToListAsync(); var currentWithFlag = currentSelection .Where(pts => flag == (pts.Flags & flag)) .Select(pts => new { toStay = ids.Contains(pts.TagID), pts }) .GroupBy(t => t.toStay) .Select(collection => new { collection.First().toStay, col = collection.Select(t => t.pts) }) .ToArray(); IEnumerable <int> toStay = currentWithFlag .SingleOrDefault(t => t.toStay) ?.col?.Select(pst => pst.TagID).ToList(); IEnumerable <ProfileSelectedTag> toReset = currentWithFlag .SingleOrDefault(t => !t.toStay) ?.col; toStay = toStay ?? (new List <int>()); toReset = toReset ?? (new List <ProfileSelectedTag>()); IEnumerable <ProfileSelectedTag> currentWithoutFlagToSet = currentSelection .Where(pts => flag != (pts.Flags & flag)) .Where(pts => ids.Contains(pts.TagID)) .ToList(); foreach (ProfileSelectedTag pst in currentWithoutFlagToSet) { pst.Flags = pst.Flags | flag; } List <ProfileSelectedTag> toRemove = new List <ProfileSelectedTag>(); foreach (ProfileSelectedTag pst in toReset) { if (ProfileSelectedTagFlags.None == (pst.Flags ^ flag)) { toRemove.Add(pst); } else { pst.Flags = pst.Flags ^ flag; } } context.RemoveRange(toRemove); if ((toStay.Count() + currentWithoutFlagToSet.Count()) < ids.Count()) { IEnumerable <int> alreadySetTags = new[] { toStay, currentWithoutFlagToSet.Select(pst => pst.TagID), } .SelectMany(t => t); IEnumerable <int> notSetTags = ids.Except(alreadySetTags); IEnumerable <ProfileSelectedTag> newSelections = notSetTags .Select(tagId => new ProfileSelectedTag { ID = 0, Flags = flag, BindedProfileID = profileId, TagID = tagId }); context.ProfilesTagSelection.AddRange(newSelections); } await context.SaveChangesAsync(); }