Newsbot.Collector/Newsbot.Collector.Database/Repositories/AuthorsTable.cs

67 lines
1.9 KiB
C#
Raw Permalink Normal View History

2023-08-04 23:04:09 -07:00
using Microsoft.EntityFrameworkCore;
using Newsbot.Collector.Domain.Entities;
using Newsbot.Collector.Domain.Interfaces;
namespace Newsbot.Collector.Database.Repositories;
public class AuthorsTable : IAuthorTable
{
private readonly DatabaseContext _context;
public AuthorsTable(string connectionString)
{
//_connectionString = connectionString;
_context = new DatabaseContext(connectionString);
}
public AuthorsTable(DatabaseContext context)
{
_context = context;
}
2023-08-04 23:04:09 -07:00
public async Task<AuthorEntity> NewAsync(AuthorEntity entity)
{
entity.Id = Guid.NewGuid();
_context.Authors.Add(entity);
2023-08-04 23:04:09 -07:00
await _context.SaveChangesAsync();
return entity;
}
2023-08-04 23:04:09 -07:00
public async Task<AuthorEntity> CreateIfMissingAsync(AuthorEntity entity)
{
2023-08-04 23:04:09 -07:00
var res = await GetBySourceIdAndNameAsync(entity.SourceId, entity.Name);
if (res is null)
{
entity.Id = Guid.NewGuid();
_context.Authors.Add(entity);
await _context.SaveChangesAsync();
return entity;
}
return res;
}
2023-08-04 23:04:09 -07:00
public async Task<List<AuthorEntity>> ListBySourceIdAsync(Guid sourceId)
{
2023-08-04 23:04:09 -07:00
return await _context.Authors
.Where(s => s.SourceId.Equals(sourceId)).ToListAsync();
}
2023-08-04 23:04:09 -07:00
public async Task<int> TotalPostsAsync(Guid id)
{
2023-08-04 23:04:09 -07:00
return await _context.Authors.CountAsync(x => x.Id.Equals(id));
}
public async Task<AuthorEntity?> GetBySourceIdAndNameAsync(Guid sourceId, string name)
{
return await _context.Authors
.Where(s => s.SourceId.Equals(sourceId))
2023-08-04 23:04:09 -07:00
.FirstOrDefaultAsync(n => n.Name.Equals(name));
}
2023-08-04 23:04:09 -07:00
public async Task<AuthorEntity?> GetById(Guid id)
{
return await _context.Authors.FirstOrDefaultAsync(q => q.Id.Equals(id));
}
}