using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository;
///
/// CRUD сервис с кешем в оперативке
///
///
///
public class CrudCacheRepositoryBase : CacheBase, ICrudRepository
where TDto : AsbCloudApp.Data.IId
where TEntity : class, IId
{
protected int KeySelector(TEntity entity) => entity.Id;
protected readonly ICrudRepository crudServiceBase;
public CrudCacheRepositoryBase(IAsbCloudDbContext dbContext, IMemoryCache memoryCache)
: base(dbContext, memoryCache)
{
crudServiceBase = new CrudRepositoryBase(dbContext);
}
public CrudCacheRepositoryBase(IAsbCloudDbContext dbContext, IMemoryCache memoryCache, Func, IQueryable> makeQuery)
: base(dbContext, memoryCache, makeQuery)
{
crudServiceBase = new CrudRepositoryBase(dbContext, makeQuery);
}
///
public virtual async Task InsertAsync(TDto newItem, CancellationToken token)
{
var result = await crudServiceBase.InsertAsync(newItem, token);
if (result > 0)
DropCache();
return result;
}
///
public virtual async Task InsertRangeAsync(IEnumerable dtos, CancellationToken token)
{
var result = await crudServiceBase.InsertRangeAsync(dtos, token);
if (result > 0)
DropCache();
return result;
}
///
public virtual async Task UpdateAsync(TDto dto, CancellationToken token)
{
var result = await crudServiceBase.UpdateAsync(dto, token);
if (result > 0)
DropCache();
return result;
}
///
public async Task> GetAllAsync(CancellationToken token)
{
var cache = await GetCacheAsync(token);
var dtos = cache.Select(Convert);
return dtos;
}
///
/// Синхронно получить запись по ИД
///
///
///
public TDto? GetOrDefault(int id)
{
var cache = GetCache();
var cacheItem = cache.FirstOrDefault(d => d.Id == id);
if (cacheItem is null)
return default;
var dto = Convert(cacheItem);
return dto;
}
///
public async Task GetOrDefaultAsync(int id, CancellationToken token)
{
var cache = await GetCacheAsync(token);
var cacheItem = cache.FirstOrDefault(d => d.Id == id);
if (cacheItem is null)
return default;
var dto = Convert(cacheItem);
return dto;
}
///
public virtual async Task DeleteAsync(int id, CancellationToken token)
{
var result = await crudServiceBase.DeleteAsync(id, token);
if (result > 0)
DropCache();
return result;
}
protected virtual TDto Convert(TEntity src) => src.Adapt();
protected virtual TEntity Convert(TDto src) => src.Adapt();
}