using AsbCloudApp.Data; using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { public class CrudServiceBase : ICrudService where TModel : class, AsbCloudDb.Model.IId where Tdto : AsbCloudApp.Data.IId { protected readonly IAsbCloudDbContext context; protected readonly DbSet dbSet; public List Incledes { get; } = new List(); public CrudServiceBase(IAsbCloudDbContext context) { this.context = context; dbSet = context.Set(); } public virtual async Task> GetPageAsync(int skip = 0, int take = 32, CancellationToken token = default) { var query = GetQueryWithIncludes(); var count = await query .CountAsync(token) .ConfigureAwait(false); var container = new PaginationContainer { Skip = skip, Take = take, Count = count, }; if (skip >= count) return container; var entities = await query .ToListAsync(token) .ConfigureAwait(false); container.Items = entities .Select(entity => Convert(entity)) .ToList(); return container; } public virtual async Task> GetAllAsync(CancellationToken token = default) { var query = GetQueryWithIncludes(); var entities = await query .ToListAsync(token).ConfigureAwait(false); var dto = entities.Select(entity => Convert(entity)); return dto; } public virtual async Task GetAsync(int id, CancellationToken token = default) { var query = GetQueryWithIncludes(); var entity = await query .FirstOrDefaultAsync(e => e.Id == id, token).ConfigureAwait(false); var dto = Convert(entity); return dto; } public virtual Task InsertAsync(Tdto item, CancellationToken token = default) { var entity = Convert(item); dbSet.Add(entity); return context.SaveChangesAsync(token); } public virtual Task InsertRangeAsync(IEnumerable items, CancellationToken token = default) { var entities = items.Select(i => Convert(i)); dbSet.AddRange(entities); return context.SaveChangesAsync(token); } public virtual Task UpdateAsync(int id, Tdto item, CancellationToken token = default) { var entity = Convert(item); dbSet.Update(entity); return context.SaveChangesAsync(token); } public virtual Task DeleteAsync(int id, CancellationToken token = default) { var entity = dbSet.AsNoTracking() .FirstOrDefault(e => e.Id == id); if (entity == default) return Task.FromResult(0); dbSet.Remove(entity); return context.SaveChangesAsync(token); } public virtual Task DeleteAsync(IEnumerable ids, CancellationToken token = default) { var entities = dbSet.Where(e => ids.Contains(e.Id)).AsNoTracking(); if (entities == default) return Task.FromResult(0); dbSet.RemoveRange(entities); return context.SaveChangesAsync(token); } public virtual Tdto Convert(TModel src) => src.Adapt(); public virtual TModel Convert(Tdto src) => src.Adapt(); private IQueryable GetQueryWithIncludes() { IQueryable query = dbSet; foreach (var include in Incledes) query = query.Include(include); return query; } } }