DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/CrudServiceBase.cs
2021-08-10 14:36:35 +05:00

79 lines
2.9 KiB
C#

using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class CrudServiceBase<Tdto, TModel> : ICrudService<Tdto>
where TModel : class, AsbCloudDb.Model.IId
where Tdto : AsbCloudApp.Data.IId
{
protected readonly IAsbCloudDbContext context;
protected readonly DbSet<TModel> dbSet;
public CrudServiceBase(IAsbCloudDbContext context)
{
this.context = context;
dbSet = context.Set<TModel>();
}
public virtual async Task<Tdto> GetAsync(int id, CancellationToken token = default)
{
var entity = await dbSet.FirstOrDefaultAsync(e => e.Id == id, token).ConfigureAwait(false);
var dto = entity.Adapt<Tdto>();
return dto;
}
public virtual async Task<Tdto> InsertAsync(Tdto newItem, CancellationToken token = default)
{
var newEntity = newItem.Adapt<TModel>();
var dbEntity = dbSet.Add(newEntity);
await context.SaveChangesAsync(token).ConfigureAwait(false);
return dbEntity.Entity.Adapt<Tdto>();
}
public virtual async Task<IEnumerable<Tdto>> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token = default)
{
var newEntities = newItems.Adapt<IEnumerable<TModel>>();
var dbEntities = new Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<TModel>[newItems.Count()];
for (int i = 0; i < dbEntities.Length; i++)
dbEntities[i] = dbSet.Add(newEntities.ElementAt(i));
await context.SaveChangesAsync(token).ConfigureAwait(false);
return dbEntities.Select(e => e.Entity.Adapt<Tdto>());
}
public virtual async Task<Tdto> UpdateAsync(Tdto item, CancellationToken token = default)
{
var newEntity = item.Adapt<TModel>();
var dbEntity = dbSet.Update(newEntity);
await context.SaveChangesAsync(token).ConfigureAwait(false);
return dbEntity.Entity.Adapt<Tdto>();
}
public virtual Task<int> DeleteAsync(int id, CancellationToken token = default)
{
var entity = dbSet.FirstOrDefault(e => e.Id == id);
if (entity == default)
return Task.FromResult(0);
dbSet.Remove(entity);
return context.SaveChangesAsync(token);
}
public virtual Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token = default)
{
var entities = dbSet.Where(e => ids.Contains(e.Id));
if (entities == default)
return Task.FromResult(0);
dbSet.RemoveRange(entities);
return context.SaveChangesAsync(token);
}
}
}