using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Infrastructure; using Microsoft.EntityFrameworkCore; using OpenAuth.Repository.Core; using OpenAuth.Repository.Interface; using Z.EntityFramework.Plus; namespace OpenAuth.Repository { public class BaseRepository : IRepository where T : BaseEntity where TDbContext: DbContext { private TDbContext _context; public BaseRepository(TDbContext context) { _context = context; } /// /// 根据过滤条件,获取记录 /// /// The exp. public IQueryable Find(Expression> exp = null) { return Filter(exp); } public bool Any(Expression> exp) { return _context.Set().Any(exp); } /// /// 查找单个,且不被上下文所跟踪 /// public T FirstOrDefault(Expression> exp) { return _context.Set().AsNoTracking().FirstOrDefault(exp); } /// /// 得到分页记录 /// /// The pageindex. /// The pagesize. /// 排序,格式如:"Id"/"Id descending" public IQueryable Find(int pageindex, int pagesize, string orderby = "", Expression> exp = null) { if (pageindex < 1) pageindex = 1; if (string.IsNullOrEmpty(orderby)) orderby = "Id descending"; return Filter(exp).OrderBy(orderby).Skip(pagesize * (pageindex - 1)).Take(pagesize); } /// /// 根据过滤条件获取记录数 /// public int Count(Expression> exp = null) { return Filter(exp).Count(); } public void Add(T entity) { if (entity.KeyIsNull()) { entity.GenerateDefaultKeyVal(); } _context.Set().Add(entity); Save(); _context.Entry(entity).State = EntityState.Detached; } /// /// 批量添加 /// /// The entities. public void BatchAdd(T[] entities) { foreach (var entity in entities) { if (entity.KeyIsNull()) { entity.GenerateDefaultKeyVal(); } } _context.Set().AddRange(entities); Save(); } public void Update(T entity) { var entry = this._context.Entry(entity); entry.State = EntityState.Modified; //如果数据没有发生变化 if (!this._context.ChangeTracker.HasChanges()) { return; } Save(); } public void Delete(T entity) { _context.Set().Remove(entity); Save(); } /// /// 实现按需要只更新部分更新 /// 如:Update(u =>u.Id==1,u =>new User{Name="ok"}); /// /// The where. /// The entity. public void Update(Expression> where, Expression> entity) { _context.Set().Where(where).Update(entity); } public virtual void Delete(Expression> exp) { _context.Set().Where(exp).Delete(); } public void Save() { try { var entities = _context.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified) .Select(e => e.Entity); foreach (var entity in entities) { var validationContext = new ValidationContext(entity); Validator.ValidateObject(entity, validationContext, validateAllProperties: true); } _context.SaveChanges(); } catch (ValidationException exc) { Console.WriteLine($"{nameof(Save)} validation exception: {exc?.Message}"); throw (exc.InnerException as Exception ?? exc); } catch (Exception ex) //DbUpdateException { throw (ex.InnerException as Exception ?? ex); } } private IQueryable Filter(Expression> exp) { var dbSet = _context.Set().AsNoTracking().AsQueryable(); if (exp != null) dbSet = dbSet.Where(exp); return dbSet; } public int ExecuteSqlRaw(string sql) { return _context.Database.ExecuteSqlRaw(sql); } /// /// 使用SQL脚本查询 /// /// public IQueryable FromSql(string sql, params object[] parameters) { return _context.Set().FromSqlRaw(sql, parameters); } /// /// 使用SQL脚本查询 /// /// [Obsolete("最新版同FromSql,需要在DbContext中设置modelBuilder.Entity().HasNoKey();")] public IQueryable Query(string sql, params object[] parameters) { return _context.Set().FromSqlRaw(sql, parameters); } #region 异步实现 /// /// 异步执行sql /// /// /// public async Task ExecuteSqlRawAsync(string sql) { return await _context.Database.ExecuteSqlRawAsync(sql); } public async Task AddAsync(T entity) { if (entity.KeyIsNull()) { entity.GenerateDefaultKeyVal(); } _context.Set().Add(entity); return await SaveAsync(); //_context.Entry(entity).State = EntityState.Detached; } public async Task BatchAddAsync(T[] entities) { foreach (var entity in entities) { if (entity.KeyIsNull()) { entity.GenerateDefaultKeyVal(); } } await _context.Set().AddRangeAsync(entities); return await SaveAsync(); } /// /// 异步更新 /// /// /// public async Task UpdateAsync(T entity) { var entry = this._context.Entry(entity); entry.State = EntityState.Modified; //如果数据没有发生变化 if (!this._context.ChangeTracker.HasChanges()) { return 0; } return await SaveAsync(); } /// /// 异步删除 /// /// /// public async Task DeleteAsync(T entity) { _context.Set().Remove(entity); return await SaveAsync(); } /// /// 异步保存 /// /// /// public async Task SaveAsync() { try { var entities = _context.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified) .Select(e => e.Entity); foreach (var entity in entities) { var validationContext = new ValidationContext(entity); Validator.ValidateObject(entity, validationContext, validateAllProperties: true); } return await _context.SaveChangesAsync(); } catch (ValidationException exc) { Console.WriteLine($"{nameof(Save)} validation exception: {exc?.Message}"); throw (exc.InnerException as Exception ?? exc); } catch (Exception ex) //DbUpdateException { throw (ex.InnerException as Exception ?? ex); } } /// /// 根据过滤条件获取记录数 /// public async Task CountAsync(Expression> exp = null) { return await Filter(exp).CountAsync(); } public async Task AnyAsync(Expression> exp) { return await _context.Set().AnyAsync(exp); } /// /// 查找单个,且不被上下文所跟踪 /// public async Task FirstOrDefaultAsync(Expression> exp) { return await _context.Set().AsNoTracking().FirstOrDefaultAsync(exp); } #endregion } }