Files
WebNovelPortal/DBConnection/Repositories/NovelRepository.cs
littlefoot e6d6b629db
Some checks failed
continuous-integration/drone/push Build is failing
db changes and build pipeline
2022-07-15 12:21:37 -04:00

87 lines
2.7 KiB
C#

using DBConnection.Models;
using DBConnection.Repositories.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace DBConnection.Repositories;
public class NovelRepository : BaseRepository<Novel>, 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<Novel> Upsert(Novel entity)
{
var dbEntity = await GetIncluded(entity) ?? entity;
// Author
dbEntity.Author = await _authorRepository.GetIncluded(entity.Author) ?? entity.Author;
//Tags
List<Tag> newTags = new List<Tag>();
foreach (var tag in entity.Tags)
{
newTags.Add(await _tagRepository.GetIncluded(tag) ?? tag);
}
dbEntity.Tags.Clear();
dbEntity.Tags = newTags;
//chapters
var newChapters = new List<Chapter>();
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<Novel> GetAllIncludedQueryable()
{
return DbContext.Novels
.Include(i => i.Author)
.Include(i => i.Chapters)
.Include(i => i.Tags);
}
public async Task<Novel?> GetNovel(Guid guid)
{
return await GetIncluded(i => i.Guid == guid);
}
public async Task<Novel?> GetNovel(string url)
{
return await GetIncluded(i => i.Url == url);
}
public async Task<IEnumerable<Novel>> LookupNovelsByName(string name)
{
return await GetWhereIncluded(n => n.Title.Contains(name));
}
public async Task<IEnumerable<Novel>> LookupNovelsByTag(string tag)
{
return await GetWhereIncluded(n => n.Tags.Any(nt => nt.TagValue.Contains(tag)));
}
}