Files
ersatztv/ErsatzTV.Infrastructure/Data/Repositories/ConfigElementRepository.cs
T
Jason DoveandGitHub 0fb5bfde58 refactor dbcontext lifetime (#258)
* refactor create playout handler

* refactor get all playouts handler

* refactor delete playout handler

* remove dead code

* ignore unnamed artists for collections

* more repository cleanup

* more schedule items refactoring

* more playout refactoring

* refactor playout builder

* refactor ffmpeg profiles

* more ffmpeg profile refactoring

* rework resolutions

* refactor media collections

* refactor config elements

* update changelog

* more cleanup
2021-06-13 20:19:10 -05:00

68 lines
2.4 KiB
C#

using System;
using System.Linq;
using System.Threading.Tasks;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Infrastructure.Extensions;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using static LanguageExt.Prelude;
namespace ErsatzTV.Infrastructure.Data.Repositories
{
public class ConfigElementRepository : IConfigElementRepository
{
private readonly IDbContextFactory<TvContext> _dbContextFactory;
public ConfigElementRepository(IDbContextFactory<TvContext> dbContextFactory) =>
_dbContextFactory = dbContextFactory;
public async Task<Unit> Upsert<T>(ConfigElementKey configElementKey, T value)
{
await using TvContext dbContext = _dbContextFactory.CreateDbContext();
Option<ConfigElement> maybeElement = await dbContext.ConfigElements
.SelectOneAsync(c => c.Key, c => c.Key == configElementKey.Key);
await maybeElement.Match(
async element =>
{
element.Value = value.ToString();
await dbContext.SaveChangesAsync();
},
async () =>
{
var configElement = new ConfigElement
{
Key = configElementKey.Key,
Value = value.ToString()
};
await dbContext.ConfigElements.AddAsync(configElement);
await dbContext.SaveChangesAsync();
});
return Unit.Default;
}
public async Task<Option<ConfigElement>> Get(ConfigElementKey key)
{
await using TvContext dbContext = _dbContextFactory.CreateDbContext();
return await dbContext.ConfigElements
.OrderBy(ce => ce.Key)
.SingleOrDefaultAsync(ce => ce.Key == key.Key)
.Map(Optional);
}
public Task<Option<T>> GetValue<T>(ConfigElementKey key) =>
Get(key).MapT(ce => (T) Convert.ChangeType(ce.Value, typeof(T)));
public async Task Delete(ConfigElement configElement)
{
await using TvContext dbContext = _dbContextFactory.CreateDbContext();
dbContext.ConfigElements.Remove(configElement);
await dbContext.SaveChangesAsync();
}
}
}