using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace Repository { public class LogRepository : IRepository { public DbContext GetCurrentDbContext() { var context = new LogDbContext(); return context; } public bool Add(T entity) where T : class { using var context = GetCurrentDbContext(); context.Set().Add(entity); var count = context.SaveChanges(); return count > 0; } public async Task AddAsync(T entity) where T : class { await using var context = GetCurrentDbContext(); await context.Set().AddAsync(entity); var count = await context.SaveChangesAsync(); return count > 0; } public bool AddRange(IEnumerable entity) where T : class { using var context = GetCurrentDbContext(); context.Set().AddRange(entity); var count = context.SaveChanges(); return count > 0; } public async Task AddRangeAsync(IEnumerable entity) where T : class { await using var context = GetCurrentDbContext(); await context.Set().AddRangeAsync(entity); var count = await context.SaveChangesAsync(); return count > 0; } public bool Delete(T entity) where T : class { using var context = GetCurrentDbContext(); context.Set().Attach(entity); context.Set().Remove(entity); var count = context.SaveChanges(); return count > 0; } public bool DeleteAll() where T : class { using var context = GetCurrentDbContext(); var entities = context.Set().ToArray(); if (entities.Length == 0) { return false; } context.Set().RemoveRange(entities); var count = context.SaveChanges(); return true; } public async Task DeleteAllAsync() where T : class { await using var context = GetCurrentDbContext(); var entities = await context.Set().ToArrayAsync(); if (entities.Length == 0) { return false; } context.Set().RemoveRange(entities); var count = context.SaveChanges(); return true; } public bool Delete(Expression> whereLambda) where T : class { using var context = GetCurrentDbContext(); var entityModel = context.Set().Where(whereLambda).FirstOrDefault(); if (entityModel == null) return false; context.Set().Remove(entityModel); var count = context.SaveChanges(); return count > 0; } public async Task DeleteAsync(Expression> whereLambda) where T : class { await using var context = GetCurrentDbContext(); var entityModel = await context.Set().Where(whereLambda).FirstOrDefaultAsync(); if (entityModel == null) return false; context.Set().Remove(entityModel); var count = await context.SaveChangesAsync(); return count > 0; } public bool DeleteById(dynamic id) where T : class { using var context = GetCurrentDbContext(); var entityModel = context.Set().Find(id); if (entityModel == null) return false; context.Set().Remove(entityModel); var count = context.SaveChanges(); return count > 0; } public async Task DeleteByIdAsync(dynamic id) where T : class { await using var context = GetCurrentDbContext(); var entityModel = await context.Set().FindAsync(id); if (entityModel == null) return false; context.Set().Remove(entityModel); var count = await context.SaveChangesAsync(); return count > 0; } public bool Update(T entity) where T : class { using var context = GetCurrentDbContext(); var entityModel = context.Entry(entity); context.Set().Attach(entity); entityModel.State = EntityState.Modified; var count = context.SaveChanges(); return count > 0; } public async Task UpdateAsync(T entity) where T : class { await using var context = GetCurrentDbContext(); var entityModel = context.Entry(entity); context.Set().Attach(entity); entityModel.State = EntityState.Modified; var count = await context.SaveChangesAsync(); return count > 0; } public bool Update(List entities) where T : class { using var context = GetCurrentDbContext(); if (entities != null) { foreach (var item in entities) { var entityModel = context.Entry(entities); context.Set().Attach(item); entityModel.State = EntityState.Modified; } } var count = context.SaveChanges(); return count > 0; } //查询要修改的数据 public bool Update(T model, Expression> whereLambda, params string[] modifiedProNames) where T : class { using var context = GetCurrentDbContext(); var listModifying = context.Set().Where(whereLambda).ToList(); var t = typeof(T); var proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); var ditProList = new Dictionary(); proInfos.ForEach(p => { if (modifiedProNames.Contains(p.Name)) { ditProList.Add(p.Name, p); } }); if (ditProList.Count <= 0) { throw new Exception("指定修改的字段名称有误或为空"); } foreach (var item in ditProList) { var proInfo = item.Value; var newValue = proInfo.GetValue(model, null); //批量进行修改相互对应的属性 foreach (var oModel in listModifying) { proInfo.SetValue(oModel, newValue, null);//设置其中新的值 } } return context.SaveChanges() > 0; } public T FindById(dynamic id) where T : class { using var context = GetCurrentDbContext(); return context.Set().Find(id); } public async Task FindByIdAsync(dynamic id) where T : class { await using var context = GetCurrentDbContext(); return await context.Set().FindAsync(id); } public T GetFirstDefault(Expression> whereLambda = null) where T : class { using var context = GetCurrentDbContext(); return whereLambda != null ? context.Set().Where(whereLambda).FirstOrDefault() : context.Set().FirstOrDefault(); } public async Task GetFirstDefaultAsync(Expression> whereLambda = null) where T : class { await using var context = GetCurrentDbContext(); return whereLambda != null ? await context.Set().Where(whereLambda).FirstOrDefaultAsync() : await context.Set().FirstOrDefaultAsync(); } public List GetAll(string orderProperty = null) where T : class { using var context = GetCurrentDbContext(); if (orderProperty == null) { return context.Set().ToList(); } var properties = typeof(T).GetProperties().Select(c => c.Name); if (!properties.Contains(orderProperty)) { throw new Exception("Not Find Property Exception"); } return context.Set().OrderBy(c => c.GetType().GetProperties().First(p => p.Name == orderProperty)) .ToList(); } public async Task> GetAllAsync(string orderProperty = null) where T : class { await using var context = GetCurrentDbContext(); if (orderProperty == null) { return await context.Set().ToListAsync(); } var properties = typeof(T).GetProperties().Select(c => c.Name); if (!properties.Contains(orderProperty)) { throw new Exception("Not Find Property Exception"); } return await context.Set().OrderBy(c => c.GetType().GetProperties().First(p => p.Name == orderProperty)) .ToListAsync(); } public List GetAllQuery(string path, Expression> whereLambda = null) where T : class { using var context = GetCurrentDbContext(); return whereLambda != null ? context.Set().Where(whereLambda).Include(path).ToList() : context.Set().Include(path).ToList(); } public List GetAllQuery(Expression> whereLambda = null) where T : class { using var context = GetCurrentDbContext(); return whereLambda != null ? context.Set().Where(whereLambda).ToList() : context.Set().ToList(); } public async Task> GetAllQueryAsync(Expression> whereLambda = null) where T : class { await using var context = GetCurrentDbContext(); return await (whereLambda != null ? context.Set().Where(whereLambda).ToListAsync() : context.Set().ToListAsync()); } public int GetCount(Expression> whereLambda = null) where T : class { using var context = GetCurrentDbContext(); return whereLambda != null ? context.Set().Where(whereLambda).Count() : context.Set().Count(); } public async Task GetCountAsync(Expression> whereLambda = null) where T : class { await using var context = GetCurrentDbContext(); return await (whereLambda != null ? context.Set().Where(whereLambda).CountAsync() : context.Set().CountAsync()); } public bool GetAny(Expression> whereLambda = null) where T : class { using var context = GetCurrentDbContext(); return whereLambda != null ? context.Set().Where(whereLambda).Any() : context.Set().Any(); } public async Task GetAnyAsync(Expression> whereLambda = null) where T : class { await using var context = GetCurrentDbContext(); return await (whereLambda != null ? context.Set().Where(whereLambda).AnyAsync() : context.Set().AnyAsync()); } public List Pagination(int pageIndex, int pageSize, Expression> orderBy, Expression> whereLambda = null, bool isOrder = true) where T : class { using var context = GetCurrentDbContext(); IQueryable queryList = isOrder ? context.Set().OrderBy(orderBy) : context.Set().OrderByDescending(orderBy); if (whereLambda != null) { queryList = queryList.Where(whereLambda); } return queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); } public async Task> PaginationAsync(int pageIndex, int pageSize, Expression> orderBy, Expression> whereLambda = null, bool isOrder = true) where T : class { await using var context = GetCurrentDbContext(); IQueryable queryList = isOrder ? context.Set().OrderBy(orderBy) : context.Set().OrderByDescending(orderBy); if (whereLambda != null) { queryList = queryList.Where(whereLambda); } return await queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToListAsync(); } public List Pagination(int pageIndex, int pageSize, string ordering, Expression> whereLambda = null) where T : class { var ditProList = new Dictionary(); using var context = GetCurrentDbContext(); var t = typeof(T); var proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); proInfos.ForEach(p => { ditProList.Add(p.Name, p); }); //分页的时候一定要注意 Order 一定在Skip 之前 var queryList = context.Set() .OrderBy(c => c.GetType().GetProperties().First(p => p.Name == ordering).Name); if (whereLambda != null) { queryList = (IOrderedQueryable)queryList.Where(whereLambda); } return queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); } public async Task> PaginationAsync(int pageIndex, int pageSize, string ordering, Expression> whereLambda = null) where T : class { await using var context = GetCurrentDbContext(); var t = typeof(T); var proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); var ditProList = new Dictionary(); proInfos.ForEach(p => { ditProList.Add(p.Name, p); }); //分页的时候一定要注意 Order 一定在Skip 之前 var queryList = context.Set() .OrderBy(c => c.GetType().GetProperties().First(p => p.Name == ordering).Name); if (whereLambda != null) { queryList = (IOrderedQueryable)queryList.Where(whereLambda); } return await queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToListAsync(); } public List GetSelect(Expression> whereLambda) where T : class { using var context = GetCurrentDbContext(); return context.Set().Where(whereLambda).ToList(); } public List QueryPro(string sql, List parameters, CommandType cmdType = CommandType.Text) where T : class { using var context = GetCurrentDbContext(); if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } var array = parameters.ToArray(); var sqlParams = array.Select(item => item).Cast().ToList(); //进行执行存储过程 if (cmdType != CommandType.StoredProcedure) return context.Set().FromSqlRaw(sql, sqlParams).ToList(); var paraNames = new StringBuilder(); foreach (var item in parameters) { paraNames.Append($" @{item},"); } sql = paraNames.Length > 0 ? $"exec {sql} {paraNames.ToString().Trim(',')}" : $"exec {sql} "; return context.Set().FromSqlRaw(sql, sqlParams).ToList(); } public void RollBackChanges() where T : class { using var context = GetCurrentDbContext(); var query = context.ChangeTracker.Entries().ToList(); query.ForEach(p => p.State = EntityState.Unchanged); } public bool Update(Expression> whereLambda, Expression> updateLambda) where T : class { throw new NotImplementedException(); } public Task UpdateAsync(Expression> whereLambda, Expression> updateLambda) where T : class { throw new NotImplementedException(); } } }