54 lines
1.6 KiB
C#
54 lines
1.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Mapster;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
using Newtonsoft.Json.Linq;
|
|
using Persistence.Database.Entity;
|
|
using Persistence.Models;
|
|
using Persistence.Repositories;
|
|
|
|
namespace Persistence.Repository.Repositories;
|
|
public class DataSourceSystemRepository : IDataSourceSystemRepository
|
|
{
|
|
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
|
|
private DbContext db;
|
|
private readonly IMemoryCache memoryCache;
|
|
private const int CacheExpirationInMinutes = 60;
|
|
public DataSourceSystemRepository(DbContext db, IMemoryCache memoryCache)
|
|
{
|
|
this.db = db;
|
|
this.memoryCache = memoryCache;
|
|
}
|
|
protected virtual IQueryable<DataSourceSystem> GetQueryReadOnly() => db.Set<DataSourceSystem>();
|
|
|
|
public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
|
|
{
|
|
var entity = dataSourceSystemDto.Adapt<DataSourceSystem>();
|
|
|
|
await db.Set<DataSourceSystem>().AddAsync(entity);
|
|
await db.SaveChangesAsync(token);
|
|
|
|
memoryCache.Remove(SystemCacheKey);
|
|
}
|
|
|
|
public async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
|
|
{
|
|
var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f =>
|
|
{
|
|
f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes);
|
|
|
|
var query = GetQueryReadOnly();
|
|
var entities = await query.ToListAsync(token);
|
|
var dtos = entities.Select(e => e.Adapt<DataSourceSystemDto>());
|
|
|
|
return dtos;
|
|
});
|
|
|
|
return systems ?? [];
|
|
}
|
|
}
|