private async Task AddVersionTagsAsync(Common.Api.Request.MediaPart requestedPart) { if (requestedPart.Version.Tags != null) { List <Dal.Model.MediaTag> tagsInRequestVersion = new(); foreach (var reqVersionTag in requestedPart.Version.Tags) { var tag = await context.MediaTags.SingleOrDefaultAsync(t => t.Name == reqVersionTag.Name); if (tag == null) { tag = new Dal.Model.MediaTag { Name = reqVersionTag.Name }; await context.MediaTags.AddAsync(tag); await context.SaveChangesAsync(); } tagsInRequestVersion.Add(tag); // Version-Tag link if (!await context.MediaVersionTags.AnyAsync(vt => vt.MediaVersionId == (int)requestedPart.Version.MediaVersionId && vt.MediaTagId == tag.MediaTagId)) { await context.MediaVersionTags.AddAsync(new Dal.Model.MediaVersionTag { MediaVersionId = (int)requestedPart.Version.MediaVersionId, MediaTagId = tag.MediaTagId }); await context.SaveChangesAsync(); } } // Remove tags that are not in request. var allTagsForVersion = await context.MediaVersionTags.Where(vt => vt.MediaVersionId == (int)requestedPart.Version.MediaVersionId).ToListAsync(); context.MediaVersionTags.RemoveRange(allTagsForVersion.Where(versionTag => !tagsInRequestVersion.Any(requestTag => requestTag.MediaTagId == versionTag.MediaTagId))); await context.SaveChangesAsync(); } }
private async Task AddHeaderTagsAsync(Common.Api.Request.MediaHeader requestedHeader) { if (requestedHeader.Tags != null) { List <Dal.Model.MediaTag> tagsInRequestHeader = new(); foreach (var reqHeaderTag in requestedHeader.Tags) { var tag = await context.MediaTags.SingleOrDefaultAsync(t => t.Name == reqHeaderTag.Name); if (tag == null) { tag = new Dal.Model.MediaTag { Name = reqHeaderTag.Name }; await context.MediaTags.AddAsync(tag); await context.SaveChangesAsync(); } tagsInRequestHeader.Add(tag); // Header-Tag link if (!await context.MediaHeaderTags.AnyAsync(ht => ht.MediaHeaderId == (int)requestedHeader.MediaHeaderId && ht.MediaTagId == tag.MediaTagId)) { await context.MediaHeaderTags.AddAsync(new Dal.Model.MediaHeaderTag { MediaHeaderId = (int)requestedHeader.MediaHeaderId, MediaTagId = tag.MediaTagId }); await context.SaveChangesAsync(); } } // Remove tags that are not in request. var allTagsForHeader = await context.MediaHeaderTags.Where(ht => ht.MediaHeaderId == (int)requestedHeader.MediaHeaderId).ToListAsync(); context.MediaHeaderTags.RemoveRange(allTagsForHeader.Where(headerTag => !tagsInRequestHeader.Any(requestTag => requestTag.MediaTagId == headerTag.MediaTagId))); await context.SaveChangesAsync(); } }