using DBConnection.Contexts; using DBConnection.Repositories.Interfaces; using Microsoft.EntityFrameworkCore; using Treestar.Shared.Models.DBDomain; namespace DBConnection.Repositories; public class NovelRepository : BaseRepository, INovelRepository { private readonly IAuthorRepository _authorRepository; private readonly ITagRepository _tagRepository; private readonly IChapterRepository _chapterRepository; public NovelRepository(AppDbContext dbContext, IAuthorRepository authorRepository, ITagRepository tagRepository, IChapterRepository chapterRepository) : base(dbContext) { _authorRepository = authorRepository; _tagRepository = tagRepository; _chapterRepository = chapterRepository; } public override async Task Upsert(Novel entity, bool saveAfter=true) { var dbEntity = await GetIncluded(entity) ?? entity; // Author if (entity.Author != null) { entity.Author = await _authorRepository.Upsert(entity.Author, false); } //Tags var newTags = await _tagRepository.UpsertMany(entity.Tags, false); //chapters are getting deleted now that their required... var newChapters = await _chapterRepository.UpsertMany(entity.Chapters, false); // update in db entity.Guid = dbEntity.Guid; DbContext.Entry(dbEntity).CurrentValues.SetValues(entity); dbEntity.Tags.Clear(); dbEntity.Tags.AddRange(newTags); dbEntity.Chapters.Clear(); dbEntity.Chapters.AddRange(newChapters); if (DbContext.Entry(dbEntity).State == EntityState.Detached) { dbEntity.Guid = Guid.NewGuid(); DbContext.Add(dbEntity); } if (saveAfter) { 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))); } }