using AutoMapper; using DMS.Core.Helper; using DMS.Infrastructure.Interfaces; using DMS.Infrastructure.Data; using SqlSugar; using System.Diagnostics; using System.Linq.Expressions; namespace DMS.Infrastructure.Repositories; public abstract class BaseRepository where TEntity : class, new() where TModel : class, new() { protected readonly IMapper _mapper; private readonly SqlSugarDbContext dbContext; protected SqlSugarClient Db => dbContext.GetInstance(); protected BaseRepository(IMapper mapper, ITransaction transaction) { _mapper = mapper; this.dbContext = dbContext; } public virtual async Task AddAsync(TModel model) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var entity = _mapper.Map(model); var result = await Db.Insertable(entity).ExecuteCommandAsync(); stopwatch.Stop(); NlogHelper.Info($"Add {typeof(TModel).Name}耗时:{stopwatch.ElapsedMilliseconds}ms"); return result; } public virtual async Task UpdateAsync(TModel model) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var entity = _mapper.Map(model); var result = await Db.Updateable(entity).ExecuteCommandAsync(); stopwatch.Stop(); NlogHelper.Info($"Update {typeof(TModel).Name}耗时:{stopwatch.ElapsedMilliseconds}ms"); return result; } public virtual async Task DeleteAsync(TModel model) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var entity = _mapper.Map(model); var result = await Db.Deleteable(entity).ExecuteCommandAsync(); stopwatch.Stop(); NlogHelper.Info($"Delete {typeof(TModel).Name}耗时:{stopwatch.ElapsedMilliseconds}ms"); return result; } public virtual async Task> GetAllAsync() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var entities = await Db.Queryable().ToListAsync(); stopwatch.Stop(); NlogHelper.Info($"GetAll {typeof(TModel).Name}耗时:{stopwatch.ElapsedMilliseconds}ms"); return _mapper.Map>(entities); } public virtual async Task GetByIdAsync(int id) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var entity = await Db.Queryable().In(id).FirstAsync(); stopwatch.Stop(); NlogHelper.Info($"GetById {typeof(TModel).Name}耗时:{stopwatch.ElapsedMilliseconds}ms"); return _mapper.Map(entity); } public virtual async Task GetByConditionAsync(Expression> expression) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var entity = await Db.Queryable().FirstAsync(expression); stopwatch.Stop(); NlogHelper.Info($"GetByCondition {typeof(TModel).Name}耗时:{stopwatch.ElapsedMilliseconds}ms"); return _mapper.Map(entity); } }