using DBConnection.Models; using DBConnection.Repositories.Interfaces; using Microsoft.EntityFrameworkCore; namespace DBConnection.Repositories; public class NovelRepository : BaseRepository, INovelRepository { private readonly IAuthorRepository _authorRepository; private readonly ITagRepository _tagRepository; public NovelRepository(AppDbContext dbContext, IAuthorRepository authorRepository, ITagRepository tagRepository) : base(dbContext) { _authorRepository = authorRepository; _tagRepository = tagRepository; } public override async Task Upsert(Novel entity) { var dbEntity = await GetIncluded(entity) ?? entity; // Author dbEntity.Author = await _authorRepository.GetIncluded(entity.Author) ?? entity.Author; //Tags List newTags = new List(); foreach (var tag in entity.Tags) { newTags.Add(await _tagRepository.GetIncluded(tag) ?? tag); } dbEntity.Tags.Clear(); dbEntity.Tags = newTags; //chapters var newChapters = new List(); foreach (var chapter in entity.Chapters.ToList()) { var existingChapter = await DbContext.Chapters.FindAsync(chapter.Url); if (existingChapter == null) { newChapters.Add(chapter); } else { existingChapter.Name = chapter.Name; existingChapter.DateUpdated = chapter.DateUpdated; newChapters.Add(existingChapter); } } dbEntity.Chapters.Clear(); dbEntity.Chapters = newChapters; // update in db if (DbContext.Entry(dbEntity).State == EntityState.Detached) { dbEntity.Guid = Guid.NewGuid(); DbContext.Add(dbEntity); } await DbContext.SaveChangesAsync(); return dbEntity; } protected override IQueryable GetAllIncludedQueryable() { return DbContext.Novels .Include(i => i.Author) .Include(i => i.Chapters) .Include(i => i.Tags); } public async Task GetNovel(Guid guid) { return await GetIncluded(i => i.Guid == guid); } public async Task GetNovel(string url) { return await GetIncluded(i => i.Url == url); } public async Task> LookupNovelsByName(string name) { return await GetWhereIncluded(n => n.Title.Contains(name)); } public async Task> LookupNovelsByTag(string tag) { return await GetWhereIncluded(n => n.Tags.Any(nt => nt.TagValue.Contains(tag))); } }