宁波既有建筑外墙脱落问卷调查
This commit is contained in:
678
20220330_Vote/Ewide.Core/SqlSugar/SqlSugarRepository.cs
Normal file
678
20220330_Vote/Ewide.Core/SqlSugar/SqlSugarRepository.cs
Normal file
@@ -0,0 +1,678 @@
|
||||
using Furion;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Ewide.Core
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// SqlSugar 仓储实现类
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
public partial class SqlSugarRepository<TEntity>
|
||||
where TEntity : class, new()
|
||||
{
|
||||
private readonly string[] UpdateIgnoreColumns = new string[] { "CreatedTime", "CreatedUserId", "CreatedUserName" };
|
||||
|
||||
#region 属性
|
||||
/// <summary>
|
||||
/// 初始化 SqlSugar 客户端
|
||||
/// </summary>
|
||||
private readonly SqlSugarScope _db;
|
||||
|
||||
/// <summary>
|
||||
/// 数据库上下文
|
||||
/// </summary>
|
||||
public virtual SqlSugarScope Context { get; }
|
||||
/// <summary>
|
||||
/// 独立数据库上下文
|
||||
/// </summary>
|
||||
public virtual SqlSugarProvider EntityContext { get; }
|
||||
/// <summary>
|
||||
/// 构造函数
|
||||
/// </summary>
|
||||
/// <param name="db"></param>
|
||||
public SqlSugarRepository(ISqlSugarClient db)
|
||||
{
|
||||
Context = _db = (SqlSugarScope)db;
|
||||
EntityContext = _db.GetConnectionWithAttr<TEntity>();
|
||||
Ado = EntityContext.Ado;
|
||||
}
|
||||
/// <summary>
|
||||
/// 实体集合
|
||||
/// </summary>
|
||||
public virtual ISugarQueryable<TEntity> Entities => EntityContext.Queryable<TEntity>();
|
||||
|
||||
/// <summary>
|
||||
/// 原生 Ado 对象
|
||||
/// </summary>
|
||||
public virtual IAdo Ado { get; }
|
||||
#endregion
|
||||
|
||||
#region 查询
|
||||
/// <summary>
|
||||
/// 获取总数
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public int Count(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.Count(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取总数
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public Task<int> CountAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.CountAsync(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查是否存在
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public bool Any(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.Any(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查是否存在
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<bool> AnyAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return await Entities.AnyAsync(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过主键获取实体
|
||||
/// </summary>
|
||||
/// <param name="Id"></param>
|
||||
/// <returns></returns>
|
||||
public TEntity Single(dynamic Id)
|
||||
{
|
||||
return Entities.InSingle(Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个实体
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public TEntity Single(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.Single(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个实体
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.SingleAsync(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个实体
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.First(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个实体
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return await Entities.FirstAsync(whereExpression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取列表
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<TEntity> ToList()
|
||||
{
|
||||
return Entities.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取列表
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public List<TEntity> ToList(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.Where(whereExpression).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取列表
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <param name="orderByExpression"></param>
|
||||
/// <param name="orderByType"></param>
|
||||
/// <returns></returns>
|
||||
public List<TEntity> ToList(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
|
||||
{
|
||||
return Entities.OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取列表
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Task<List<TEntity>> ToListAsync()
|
||||
{
|
||||
return Entities.ToListAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取列表
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public Task<List<TEntity>> ToListAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.Where(whereExpression).ToListAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取列表
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <param name="orderByExpression"></param>
|
||||
/// <param name="orderByType"></param>
|
||||
/// <returns></returns>
|
||||
public Task<List<TEntity>> ToListAsync(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
|
||||
{
|
||||
return Entities.OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToListAsync();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 新增
|
||||
public virtual IInsertable<TEntity> AsInsertable(TEntity entity)
|
||||
{
|
||||
return EntityContext.Insertable(entity);
|
||||
}
|
||||
|
||||
public virtual IInsertable<TEntity> AsInsertable(params TEntity[] entities)
|
||||
{
|
||||
return EntityContext.Insertable(entities);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Insert(TEntity entity)
|
||||
{
|
||||
return EntityContext.Insertable(entity).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Insert(params TEntity[] entities)
|
||||
{
|
||||
return EntityContext.Insertable(entities).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Insert(IEnumerable<TEntity> entities)
|
||||
{
|
||||
return EntityContext.Insertable(entities.ToArray()).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录返回自增Id
|
||||
/// </summary>
|
||||
/// <param name="insertObj"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int InsertReturnIdentity(TEntity insertObj)
|
||||
{
|
||||
return EntityContext.Insertable(insertObj).ExecuteReturnIdentity();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录返回雪花Id
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual long InsertReturnSnowflakeId(TEntity entity)
|
||||
{
|
||||
return EntityContext.Insertable(entity).ExecuteReturnSnowflakeId();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录返回实体
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual TEntity InsertReturnEntity(TEntity entity)
|
||||
{
|
||||
return EntityContext.Insertable(entity).ExecuteReturnEntity();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> InsertAsync(TEntity entity)
|
||||
{
|
||||
return EntityContext.Insertable(entity).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> InsertAsync(params TEntity[] entities)
|
||||
{
|
||||
return EntityContext.Insertable(entities).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> InsertAsync(IEnumerable<TEntity> entities)
|
||||
{
|
||||
if (entities != null && entities.Any())
|
||||
{
|
||||
return EntityContext.Insertable(entities.ToArray()).ExecuteCommandAsync();
|
||||
}
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录返回自增Id
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual async Task<long> InsertReturnIdentityAsync(TEntity entity)
|
||||
{
|
||||
return await EntityContext.Insertable(entity).ExecuteReturnBigIdentityAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录返回雪花Id
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual async Task<long> InsertReturnSnowflakeIdAsync(TEntity entity)
|
||||
{
|
||||
return await EntityContext.Insertable(entity).ExecuteReturnSnowflakeIdAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增一条记录返回实体
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual async Task<TEntity> InsertReturnEntityAsync(TEntity entity)
|
||||
{
|
||||
return await EntityContext.Insertable(entity).ExecuteReturnEntityAsync();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 更新
|
||||
|
||||
/// <summary>
|
||||
/// 更新一条记录
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Update(TEntity entity)
|
||||
{
|
||||
return EntityContext.Updateable(entity).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Update(params TEntity[] entities)
|
||||
{
|
||||
return EntityContext.Updateable(entities).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
|
||||
}
|
||||
/// <summary>
|
||||
/// 更新多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Update(IEnumerable<TEntity> entities)
|
||||
{
|
||||
return EntityContext.Updateable(entities.ToArray()).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
|
||||
}
|
||||
/// <summary>
|
||||
/// 更新一条记录忽略所有Null值
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual async Task<int> UpdateIgnoreNullAsync(TEntity entity)
|
||||
{
|
||||
return await EntityContext.Updateable(entity).IgnoreColumns(true).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
|
||||
}
|
||||
/// <summary>
|
||||
/// 更新一条记录
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual async Task<int> UpdateAsync(TEntity entity)
|
||||
{
|
||||
return await EntityContext.Updateable(entity).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
|
||||
}
|
||||
/// <summary>
|
||||
/// 更新记录
|
||||
/// </summary>
|
||||
/// <param name="predicate">更新的条件</param>
|
||||
/// <param name="content">更新的内容</param>
|
||||
/// <returns></returns>
|
||||
public virtual int Update(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> content)
|
||||
{
|
||||
return EntityContext.Updateable(content).Where(predicate).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新记录
|
||||
/// </summary>
|
||||
/// <param name="predicate">更新的条件</param>
|
||||
/// <param name="content">更新的内容</param>
|
||||
/// <returns></returns>
|
||||
public virtual async Task<int> UpdateAsync(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> content)
|
||||
{
|
||||
return await EntityContext.Updateable(content).Where(predicate).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> UpdateAsync(params TEntity[] entities)
|
||||
{
|
||||
return EntityContext.Updateable(entities).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新多条记录
|
||||
/// </summary>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> UpdateAsync(IEnumerable<TEntity> entities)
|
||||
{
|
||||
return EntityContext.Updateable(entities.ToArray()).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
public virtual IUpdateable<TEntity> AsUpdateable(TEntity entity)
|
||||
{
|
||||
return EntityContext.Updateable(entity).IgnoreColumns(UpdateIgnoreColumns);
|
||||
}
|
||||
|
||||
public virtual IUpdateable<TEntity> AsUpdateable(IEnumerable<TEntity> entities)
|
||||
{
|
||||
return EntityContext.Updateable<TEntity>(entities).IgnoreColumns(UpdateIgnoreColumns);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 删除
|
||||
/// <summary>
|
||||
/// 删除一条记录
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Delete(TEntity entity)
|
||||
{
|
||||
return EntityContext.Deleteable(entity).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除一条记录
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Delete(object key)
|
||||
{
|
||||
return EntityContext.Deleteable<TEntity>().In(key).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除多条记录
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <returns></returns>
|
||||
public virtual int Delete(params object[] keys)
|
||||
{
|
||||
return EntityContext.Deleteable<TEntity>().In(keys).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自定义条件删除记录
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public int Delete(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return EntityContext.Deleteable<TEntity>().Where(whereExpression).ExecuteCommand();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除一条记录
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> DeleteAsync(TEntity entity)
|
||||
{
|
||||
return EntityContext.Deleteable(entity).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除一条记录
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> DeleteAsync(object key)
|
||||
{
|
||||
return EntityContext.Deleteable<TEntity>().In(key).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除多条记录
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<int> DeleteAsync(params object[] keys)
|
||||
{
|
||||
return EntityContext.Deleteable<TEntity>().In(keys).ExecuteCommandAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自定义条件删除记录
|
||||
/// </summary>
|
||||
/// <param name="whereExpression"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<int> DeleteAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return await EntityContext.Deleteable<TEntity>().Where(whereExpression).ExecuteCommandAsync();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 其他
|
||||
/// <summary>
|
||||
/// 根据表达式查询多条记录
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <returns></returns>
|
||||
public virtual ISugarQueryable<TEntity> Where(Expression<Func<TEntity, bool>> predicate)
|
||||
{
|
||||
return AsQueryable(predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据表达式查询多条记录
|
||||
/// </summary>
|
||||
/// <param name="condition"></param>
|
||||
/// <param name="predicate"></param>
|
||||
/// <returns></returns>
|
||||
public virtual ISugarQueryable<TEntity> Where(bool condition, Expression<Func<TEntity, bool>> predicate)
|
||||
{
|
||||
return AsQueryable().WhereIF(condition, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建查询分析器
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual ISugarQueryable<TEntity> AsQueryable()
|
||||
{
|
||||
return Entities;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建查询分析器
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <returns></returns>
|
||||
public virtual ISugarQueryable<TEntity> AsQueryable(Expression<Func<TEntity, bool>> predicate)
|
||||
{
|
||||
return Entities.Where(predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接返回数据库结果
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual List<TEntity> AsEnumerable()
|
||||
{
|
||||
return AsQueryable().ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接返回数据库结果
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <returns></returns>
|
||||
public virtual List<TEntity> AsEnumerable(Expression<Func<TEntity, bool>> predicate)
|
||||
{
|
||||
return AsQueryable(predicate).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接返回数据库结果
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual Task<List<TEntity>> AsAsyncEnumerable()
|
||||
{
|
||||
return AsQueryable().ToListAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接返回数据库结果
|
||||
/// </summary>
|
||||
/// <param name="predicate"></param>
|
||||
/// <returns></returns>
|
||||
public virtual Task<List<TEntity>> AsAsyncEnumerable(Expression<Func<TEntity, bool>> predicate)
|
||||
{
|
||||
return AsQueryable(predicate).ToListAsync();
|
||||
}
|
||||
|
||||
public virtual bool IsExists(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.Any(whereExpression);
|
||||
}
|
||||
|
||||
public virtual Task<bool> IsExistsAsync(Expression<Func<TEntity, bool>> whereExpression)
|
||||
{
|
||||
return Entities.AnyAsync(whereExpression);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 仓储事务
|
||||
/// <summary>
|
||||
/// 切换仓储(注意使用环境)
|
||||
/// </summary>
|
||||
/// <typeparam name="T">实体类型</typeparam>
|
||||
/// <returns>仓储</returns>
|
||||
public virtual SqlSugarRepository<T> Change<T>()
|
||||
where T : class, new()
|
||||
{
|
||||
return App.GetService<SqlSugarRepository<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// 当前db
|
||||
/// </summary>
|
||||
public void CurrentBeginTran()
|
||||
{
|
||||
Ado.BeginTran();
|
||||
}
|
||||
/// <summary>
|
||||
/// 当前db
|
||||
/// </summary>
|
||||
public void CurrentCommitTran()
|
||||
{
|
||||
Ado.CommitTran();
|
||||
}
|
||||
/// <summary>
|
||||
/// 当前db
|
||||
/// </summary>
|
||||
public void CurrentRollbackTran()
|
||||
{
|
||||
Ado.RollbackTran();
|
||||
}
|
||||
/// <summary>
|
||||
/// 所有db
|
||||
/// </summary>
|
||||
public void BeginTran()
|
||||
{
|
||||
Context.BeginTran();
|
||||
}
|
||||
/// <summary>
|
||||
/// 所有db
|
||||
/// </summary>
|
||||
public void CommitTran()
|
||||
{
|
||||
Context.CommitTran();
|
||||
}
|
||||
/// <summary>
|
||||
/// 所有db
|
||||
/// </summary>
|
||||
public void RollbackTran()
|
||||
{
|
||||
Context.RollbackTran();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
}
|
||||
283
20220330_Vote/Ewide.Core/SqlSugar/SqlsugarSetup.cs
Normal file
283
20220330_Vote/Ewide.Core/SqlSugar/SqlsugarSetup.cs
Normal file
@@ -0,0 +1,283 @@
|
||||
using Ewide.Core;
|
||||
using Ewide.Core.Cache;
|
||||
using Furion;
|
||||
using Furion.Logging.Extensions;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Ewide.Core
|
||||
{
|
||||
public static class SqlsugarSetup
|
||||
{
|
||||
public static void AddSqlsugarSetup(this IServiceCollection services)
|
||||
{
|
||||
var connList = App.GetConfig<List<MutiDBConnectionString>>("ConnectionStrings")?.Where(p => p.Enabled).ToList();
|
||||
|
||||
List<ConnectionConfig> connectConfigList = new();
|
||||
connList.ForEach(conn =>
|
||||
{
|
||||
connectConfigList.Add(new ConnectionConfig
|
||||
{
|
||||
ConfigId = conn.Id,
|
||||
ConnectionString = conn.ConnectionString,
|
||||
DbType = conn.DbType,
|
||||
IsAutoCloseConnection = true,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
MoreSettings = new ConnMoreSettings()
|
||||
{
|
||||
IsAutoRemoveDataCache = true//自动清理缓存
|
||||
|
||||
},
|
||||
ConfigureExternalServices = new ConfigureExternalServices()
|
||||
{
|
||||
DataInfoCacheService = new SqlSugarCache(),
|
||||
EntityNameService = (type, entity) =>
|
||||
{
|
||||
var attributes = type.GetCustomAttributes(true);
|
||||
if (attributes.Any(it => it is TableAttribute))
|
||||
{
|
||||
entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name;
|
||||
}
|
||||
},
|
||||
EntityService = (type, column) =>
|
||||
{
|
||||
var attributes = type.GetCustomAttributes(true);
|
||||
if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey
|
||||
{
|
||||
column.IsPrimarykey = true; //有哪些特性可以看 1.2 特性明细
|
||||
}
|
||||
if (attributes.Any(it => it is ColumnAttribute))
|
||||
{
|
||||
column.DbColumnName = (attributes.First(it => it is ColumnAttribute) as ColumnAttribute).Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
services.AddSqlSugar(connectConfigList.ToArray(), db =>
|
||||
{
|
||||
//处理日志事务
|
||||
db.Aop.OnLogExecuting = (sql, pars) =>
|
||||
{
|
||||
Debugger.Log(1, "", $"===================CurrentConfigId:{db.CurrentConnectionConfig.ConfigId} SqlSugar log started ===================\r\n");
|
||||
Debugger.Log(2, "语句:", sql);
|
||||
Debugger.Log(3, "参数:", string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
Debugger.Log(4, "", $"===================CurrentConfigId:{db.CurrentConnectionConfig.ConfigId} SqlSugar log end ===================\r\n");
|
||||
//App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
List<Type> types = App.EffectiveTypes.Where(a => !a.IsAbstract && a.IsClass && a.GetCustomAttributes(typeof(SugarTable), true)?.FirstOrDefault() != null).ToList();
|
||||
|
||||
SqlSugarScope sqlSugarScope = new SqlSugarScope(connectConfigList,
|
||||
//全局上下文生效
|
||||
db =>
|
||||
{
|
||||
/*
|
||||
* 默认只会配置到第一个数据库,这里按照官方文档进行多数据库/多租户文档的说明进行循环配置
|
||||
*/
|
||||
foreach (var c in connectConfigList)
|
||||
{
|
||||
var dbProvider = db.GetConnectionScope((string)c.ConfigId);
|
||||
//执行超时时间
|
||||
dbProvider.Ado.CommandTimeOut = 30;
|
||||
|
||||
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
|
||||
{
|
||||
if (sql.StartsWith("SELECT"))
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
}
|
||||
if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
}
|
||||
if (sql.StartsWith("DELETE"))
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Blue;
|
||||
}
|
||||
//Console.WriteLine("Sql:" + "\r\n\r\n" + UtilMethods.GetSqlString(c.DbType, sql, pars));
|
||||
App.PrintToMiniProfiler("SqlSugar", "Info", UtilMethods.GetSqlString(c.DbType, sql, pars));
|
||||
$"DB:{c.ConfigId}, Sql:\r\n\r\n {UtilMethods.GetSqlString(c.DbType, sql, pars)}".LogInformation();
|
||||
|
||||
|
||||
};
|
||||
|
||||
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
|
||||
{
|
||||
//// 新增操作
|
||||
//if (entityInfo.OperationType == DataFilterType.InsertByObject)
|
||||
//{
|
||||
// // 主键(long)-赋值雪花Id
|
||||
// if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
|
||||
// {
|
||||
// var id = ((dynamic)entityInfo.EntityValue).Id;
|
||||
// if (id == null || id == 0)
|
||||
// entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
|
||||
// }
|
||||
|
||||
|
||||
// if (entityInfo.PropertyName == "CreatedTime")
|
||||
// entityInfo.SetValue(DateTime.Now);
|
||||
// if (App.User != null)
|
||||
// {
|
||||
// if (entityInfo.PropertyName == "TenantId")
|
||||
// {
|
||||
// var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
|
||||
// if (tenantId == null || tenantId == 0)
|
||||
// entityInfo.SetValue(App.User.FindFirst(ClaimConst.TENANT_ID)?.Value);
|
||||
// }
|
||||
// if (entityInfo.PropertyName == "CreatedUserId")
|
||||
// {
|
||||
// var createUserId = ((dynamic)entityInfo.EntityValue).CreatedUserId;
|
||||
// if (createUserId == null || createUserId == 0)
|
||||
// entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
|
||||
// }
|
||||
|
||||
// if (entityInfo.PropertyName == "CreatedUserName")
|
||||
// entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_NAME)?.Value);
|
||||
// }
|
||||
//}
|
||||
//// 更新操作
|
||||
//if (entityInfo.OperationType == DataFilterType.UpdateByObject)
|
||||
//{
|
||||
// if (entityInfo.PropertyName == "UpdatedTime")
|
||||
// entityInfo.SetValue(DateTime.Now);
|
||||
// if (entityInfo.PropertyName == "UpdatedUserId")
|
||||
// entityInfo.SetValue(App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
|
||||
// if (entityInfo.PropertyName == "UpdatedUserName")
|
||||
// entityInfo.SetValue(App.User?.FindFirst(ClaimConst.CLAINM_NAME)?.Value);
|
||||
|
||||
//}
|
||||
};
|
||||
|
||||
/*
|
||||
* 使用 SqlSugarScope 循环配置此项的时候会覆盖整个 ConfigureExternalServices,
|
||||
* 移动到 New ConnectionConfig中配置
|
||||
*/
|
||||
//db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
|
||||
//{
|
||||
// DataInfoCacheService = new SqlSugarCache()//配置我们创建的缓存类
|
||||
//};
|
||||
|
||||
////全局过滤器
|
||||
//var superAdminViewAllData = Convert.ToBoolean(App.GetOptions<SystemSettingsOptions>().SuperAdminViewAllData);
|
||||
//foreach (var entityType in types)
|
||||
//{
|
||||
// // 配置多租户全局过滤器
|
||||
// //if (!entityType.GetProperty(ClaimConst.TENANT_ID).IsEmpty())
|
||||
// //{ //判断实体类中包含TenantId属性
|
||||
// // //构建动态Lambda
|
||||
// // var lambda = DynamicExpressionParser.ParseLambda
|
||||
// // (new[] { Expression.Parameter(entityType, "it") },
|
||||
// // typeof(bool), $"{nameof(DBEntityTenant.TenantId)} == @0 or (@1 and @2)",
|
||||
// // GetTenantId(), IsSuperAdmin(), superAdminViewAllData);
|
||||
// // dbProvider.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)); //将Lambda传入过滤器
|
||||
// //}
|
||||
// // 配置加删除全局过滤器
|
||||
// if (!entityType.GetProperty(CommonConst.DELETE_FIELD).IsEmpty())
|
||||
// { //判断实体类中包含IsDeleted属性
|
||||
// //构建动态Lambda
|
||||
// var lambda = DynamicExpressionParser.ParseLambda
|
||||
// (new[] { Expression.Parameter(entityType, "it") },
|
||||
// typeof(bool), $"{nameof(DEntityBase.IsDeleted)} == @0",
|
||||
// false);
|
||||
// dbProvider.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)
|
||||
// {
|
||||
// IsJoinQuery = true
|
||||
// }); //将Lambda传入过滤器
|
||||
// }
|
||||
//}
|
||||
|
||||
}
|
||||
});
|
||||
services.AddSingleton<ISqlSugarClient>(sqlSugarScope);
|
||||
// 注册 SqlSugar 仓储
|
||||
services.AddScoped(typeof(SqlSugarRepository<>));
|
||||
|
||||
////如果多个数数据库传 List<ConnectionConfig>
|
||||
//var configConnection = new ConnectionConfig()
|
||||
//{
|
||||
// DbType = SqlSugar.DbType.MySql,
|
||||
// ConnectionString = configuration.GetConnectionString(dbName),
|
||||
// IsAutoCloseConnection = true,
|
||||
//};
|
||||
|
||||
//SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
|
||||
// db =>
|
||||
// {
|
||||
// //单例参数配置,所有上下文生效
|
||||
// db.Aop.OnLogExecuting = (sql, pars) =>
|
||||
// {
|
||||
// //Console.WriteLine(sql);//输出sql
|
||||
// };
|
||||
// });
|
||||
|
||||
//services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 判断是不是超级管理员
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static bool IsSuperAdmin()
|
||||
{
|
||||
if (App.User == null) return false;
|
||||
return App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == AdminType.SuperAdmin.GetHashCode().ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加 SqlSugar 拓展
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="config"></param>
|
||||
/// <param name="buildAction"></param>
|
||||
/// <returns></returns>
|
||||
public static IServiceCollection AddSqlSugar(this IServiceCollection services, ConnectionConfig config, Action<ISqlSugarClient> buildAction = default)
|
||||
{
|
||||
var list = new List<ConnectionConfig>();
|
||||
list.Add(config);
|
||||
return services.AddSqlSugar(list, buildAction);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加 SqlSugar 拓展
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="configs"></param>
|
||||
/// <param name="buildAction"></param>
|
||||
/// <returns></returns>
|
||||
public static IServiceCollection AddSqlSugar(this IServiceCollection services, List<ConnectionConfig> configs, Action<ISqlSugarClient> buildAction = default)
|
||||
{
|
||||
// 注册 SqlSugar 客户端
|
||||
services.AddScoped<ISqlSugarClient>(u =>
|
||||
{
|
||||
var db = new SqlSugarClient(configs);
|
||||
buildAction?.Invoke(db);
|
||||
return db;
|
||||
});
|
||||
|
||||
// 注册 SqlSugar 仓储
|
||||
services.AddScoped(typeof(SqlSugarRepository<>));
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
public class MutiDBConnectionString
|
||||
{
|
||||
public string Id { get; set; }
|
||||
public string ConnectionString { get; set; }
|
||||
public DbType DbType { get; set; }
|
||||
public bool Enabled { get; set; }
|
||||
public string ProviderName { get; set; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user