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 : ICrudService where TModel : class, AsbCloudDb.Model.IId where Tdto : AsbCloudApp.Data.IId { protected readonly IAsbCloudDbContext context; protected readonly DbSet dbSet; public CrudServiceBase(IAsbCloudDbContext context) { this.context = context; dbSet = context.Set(); } public virtual async Task GetAsync(int id, CancellationToken token = default) { var entity = await dbSet.AsNoTracking() .FirstOrDefaultAsync(e => e.Id == id, token).ConfigureAwait(false); var dto = entity.Adapt(); return dto; } public virtual async Task InsertAsync(Tdto newItem, CancellationToken token = default) { var newEntity = newItem.Adapt(); var dbEntity = dbSet.Add(newEntity); await context.SaveChangesAsync(token).ConfigureAwait(false); return dbEntity.Entity.Adapt(); } public virtual async Task> InsertRangeAsync(IEnumerable newItems, CancellationToken token = default) { var newEntities = newItems.Adapt>(); var dbEntities = new Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry[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()); } public virtual async Task UpdateAsync(Tdto item, CancellationToken token = default) { var newEntity = item.Adapt(); var dbEntity = dbSet.Update(newEntity); await context.SaveChangesAsync(token).ConfigureAwait(false); return dbEntity.Entity.Adapt(); } 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); } } }