OpenAuth.Net/OpenAuth.Repository/BaseRepository.cs

320 lines
9.9 KiB
C#
Raw Normal View History

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