1、引入nuget包
install-package sqlSugar
2、仓储类
public class BaseRepository<TEntity> : SimpleClient<TEntity> where TEntity : class, new()
{
private Logger loggers = Logger.CreateLogger(typeof(BaseRepository<TEntity>));
public BaseRepository(ISqlSugarClient context = null) : base(context)
{
if (context == null)
{
// 分库处理
Config config = Config.getBean();
if (typeof(TEntity).GetTypeInfo().GetCustomAttributes(typeof(SugarTable), true).FirstOrDefault((x => x.GetType() == typeof(SugarTable))) is SugarTable sugarTable)
{
string conncent = sugarTable.TableDescription;
if (string.IsNullOrWhiteSpace(conncent)) { config = Config.getBean();}
else{ config = Config.getBean(conncent.ToUpper());}
}
base.Context = new SqlSugarClient(new ConnectionConfig()
{
DbType = (DbType)config.DbType,
InitKeyType = (InitKeyType)config.InitKeyType,
IsAutoCloseConnection = config.IsAutoCloseConnection,
ConnectionString = config.ConnectionString,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = new HttpRuntimeCache()
}
});
base.Context.Aop.OnLogExecuting = (sql, pars) => //SQL执行中事件
{ //loggers.Warn(new LogContent("OnLogExecuting", "SQL语句打印", "SQL:" + GetParas(pars) + "【SQL语句】:" + sql));
};
base.Context.Aop.OnError = (e) =>{
loggers.Error(new LogContent("BaseRepository", "SQL异常事件", e.Message));
};
}
}
private string GetParas(SugarParameter[] pars)
{
string key = "【SQL参数】:";
foreach (var param in pars)
{
key += $"{param.ParameterName}:{param.Value}\n";
}
return key;
}
internal ISqlSugarClient Db
{
get { return Context; }
}
public void BeginTran()
{
Context.Ado.BeginTran();
}
public void Commit()
{
Context.Ado.CommitTran();
}
public void Rollback()
{
Context.Ado.RollbackTran();
}
///
/// 功能描述:根据ID查新数据
///
/// id(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件
///
public async Task<TEntity> QueryById(object objId)
{
return await Context.Queryable<TEntity>().In(objId).SingleAsync();
}
///
/// 功能描述:根据ID查询一条数据
///
/// id(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件
/// 是否使用缓存
/// 数据实体
public async Task<TEntity> QueryById(object objId, bool blnUseCache = false)
{
return await Context.Queryable<TEntity>().WithCacheIF(blnUseCache).In(objId).SingleAsync();
}
///
/// 功能描述:根据ID查询数据
///
/// id列表(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件
/// 数据实体列表
public async Task<List<TEntity>> QueryByIDs(object[] lstIds)
{
return await Context.Queryable<TEntity>().In(lstIds).ToListAsync();
}
///
/// 写入实体数据
///
/// 实体类
///
public async Task<long> Add(TEntity entity)
{
var insert = Context.Insertable(entity);
return await insert.ExecuteReturnBigIdentityAsync();
}
///
/// 写入实体数据(同步方法)
///
/// 实体类
///
public long AddSync(TEntity entity)
{
var insert = Context.Insertable(entity);
return insert.ExecuteReturnBigIdentity();
}
///
/// 写入实体数据
///
/// 实体类
/// 指定只插入列
/// 返回自增量列
public async Task<int> Add(TEntity entity, Expression<Func<TEntity, object>> insertColumns = null)
{
var insert = Context.Insertable(entity);
if (insertColumns == null)
{
return await insert.ExecuteReturnIdentityAsync();
}
else
{
return await insert.InsertColumns(insertColumns).ExecuteReturnIdentityAsync();
}
}
///
/// 写入实体数据
///
/// 实体类
/// 返回被影响的行数
public async Task<int> AddByRows(TEntity entity)
{
var insert = Context.Insertable(entity);
return await insert.ExecuteCommandAsync();
}
///
/// 写入实体数据
///
/// 实体类集合
/// 返回被影响的行数
public int AddByRows(List<TEntity> listEntity)
{
return Context.Insertable(listEntity.ToArray()).ExecuteCommand();
}
///
/// 批量插入实体(速度快)
///
/// 实体集合
/// 影响行数
public async Task<int> Add(List<TEntity> listEntity)
{
return await Context.Insertable(listEntity.ToArray()).ExecuteCommandAsync();
}
public int AddSync(List<TEntity> listEntity)
{
return Context.Insertable(listEntity.ToArray()).ExecuteCommand();
}
///
/// 更新实体数据
///
/// 实体类
///
public async Task<bool> Update(TEntity entity)
{
//这种方式会以主键为条件
return await Context.Updateable(entity).ExecuteCommandHasChangeAsync();
}
public bool Update(List<TEntity> entities)
{
return Context.Updateable(entities).ExecuteCommandHasChange();
}
///
/// 同步 更新
///
///
///
public int UpdateSync(TEntity entity)
{
//这种方式会以主键为条件
return Context.Updateable(entity).ExecuteCommand();
}
///
/// 同步 更新批量
///
///
///
public int UpdateSync(List<TEntity> entities)
{
return Context.Updateable(entities).ExecuteCommand();
}
///
/// 异步 更新实体
///
///
///
public async Task<int> UpdateAsync(List<TEntity> entities)
{
return await Context.Updateable(entities).ExecuteCommandAsync();
}
public async Task<bool> Update(TEntity entity, string strWhere)
{
return await Context.Updateable(entity).Where(strWhere).ExecuteCommandHasChangeAsync();
}
public async Task<bool> Update(string strSql, SugarParameter[] parameters = null)
{
return await Context.Ado.ExecuteCommandAsync(strSql, parameters) > 0;
}
public async Task<bool> Update(object operateAnonymousObjects)
{
return await Context.Updateable<TEntity>(operateAnonymousObjects).ExecuteCommandAsync() > 0;
}
public async Task<bool> Update(
TEntity entity,
List<string> lstColumns = null,
List<string> lstIgnoreColumns = null,
string strWhere = ""
)
{
IUpdateable<TEntity> up = Context.Updateable(entity);
if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
{
up = up.IgnoreColumns(lstIgnoreColumns.ToArray());
}
if (lstColumns != null && lstColumns.Count > 0)
{
up = up.UpdateColumns(lstColumns.ToArray());
}
if (!string.IsNullOrEmpty(strWhere))
{
up = up.Where(strWhere);
}
return await up.ExecuteCommandHasChangeAsync();
}
///
/// 根据实体删除一条数据
///
/// 实体类
///
public async Task<bool> Delete(TEntity entity)
{
return await Context.Deleteable(entity).ExecuteCommandHasChangeAsync();
}
///
/// 删除指定ID的数据
///
/// 主键ID
///
public async Task<bool> DeleteById(object id)
{
return await Context.Deleteable<TEntity>(id).ExecuteCommandHasChangeAsync();
}
///
/// 删除指定ID集合的数据(批量删除)
///
/// 主键ID集合
///
public async Task<bool> DeleteByIds(object[] ids)
{
return await Context.Deleteable<TEntity>().In(ids).ExecuteCommandHasChangeAsync();
}
///
/// 功能描述:查询所有数据
///
/// 数据列表
public async Task<List<TEntity>> Query()
{
return await Context.Queryable<TEntity>().ToListAsync();
}
///
/// 功能描述:查询数据列表
///
/// 条件
/// 数据列表
public async Task<List<TEntity>> Query(string strWhere)
{
return await Context.Queryable<TEntity>().WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToListAsync();
}
///
/// 功能描述:查询数据列表
///
/// whereExpression
/// 数据列表
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression)
{
return await Context.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).ToListAsync();
}
public async Task<TEntity> QueryFist(Expression<Func<TEntity, bool>> whereExpression)
{
return await Context.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).FirstAsync();
}
///
/// 功能描述:查询一个列表
///
/// 条件表达式
/// 排序字段,如name asc,age desc
/// 数据列表
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, string strOrderByFileds)
{
return await Context.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).OrderByIF(strOrderByFileds != null, strOrderByFileds).ToListAsync();
}
///
/// 功能描述:查询一个列表
///
///
///
///
///
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true)
{
return await Context.Queryable<TEntity>().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToListAsync();
}
///
/// 功能描述:查询一个列表
///
/// 条件
/// 排序字段,如name asc,age desc
/// 数据列表
public async Task<List<TEntity>> Query(string strWhere, string strOrderByFileds)
{
return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToListAsync();
}
///
/// 功能描述:查询前N条数据
///
/// 条件表达式
/// 前N条
/// 排序字段,如name asc,age desc
/// 数据列表
public async Task<List<TEntity>> Query(
Expression<Func<TEntity, bool>> whereExpression,
int intTop,
string strOrderByFileds)
{
return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).Take(intTop).ToListAsync();
}
///
/// 功能描述:查询前N条数据
///
/// 条件
/// 前N条
/// 排序字段,如name asc,age desc
/// 数据列表
public async Task<List<TEntity>> Query(
string strWhere,
int intTop,
string strOrderByFileds)
{
return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).Take(intTop).ToListAsync();
}
///
/// 功能描述:分页查询
///
/// 条件表达式
/// 页码(下标0)
/// 页大小
/// 数据总量
/// 排序字段,如name asc,age desc
/// 数据列表
public async Task<List<TEntity>> Query(
Expression<Func<TEntity, bool>> whereExpression,
int intPageIndex,
int intPageSize,
string strOrderByFileds)
{
return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).ToPageListAsync(intPageIndex, intPageSize);
}
///
/// 功能描述:分页查询
///
/// 条件
/// 页码(下标0)
/// 页大小
/// 数据总量
/// 排序字段,如name asc,age desc
/// 数据列表
public async Task<List<TEntity>> Query(
string strWhere,
int intPageIndex,
int intPageSize,
string strOrderByFileds)
{
return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToPageListAsync(intPageIndex, intPageSize);
}
///
///查询-多表查询
///
/// 实体1
/// 实体2
/// 实体3
/// 返回对象
/// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
/// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
/// 查询表达式 (w1, w2) =>w1.UserNo == "")
/// 值
public async Task<List<TResult>> QueryMuch<T, T2, T3, TResult>(
Expression<Func<T, T2, T3, object[]>> joinExpression,
Expression<Func<T, T2, T3, TResult>> selectExpression,
Expression<Func<T, T2, T3, bool>> whereLambda = null) where T : class, new()
{
if (whereLambda == null)
{
return await Context.Queryable(joinExpression).Select(selectExpression).ToListAsync();
}
return await Context.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToListAsync();
}
///
/// 根据Sql查询集合
///
///
///
public async Task<List<TEntity>> QuerySql(string sql)
{
return await Context.SqlQueryable<TEntity>(sql).ToListAsync();
}
///
/// ADO 查询
///
///
///
public async Task<List<TEntity>> SqlQueryTolist(string sql)
{
return await Context.Ado.SqlQueryAsync<TEntity>(sql);
}
///
/// ADO 查询
///
///
///
public async Task<List<T>> SqlQueryTolist<T>(string sql)
{
return await Context.Ado.SqlQueryAsync<T>(sql);
}
///
/// ADO 查询
///
///
///
public async Task<TEntity> SqlQuery(string sql)
{
return await Context.Ado.SqlQuerySingleAsync<TEntity>(sql);
}
///
/// ADO 查询
///
///
///
///
public async Task<T> SqlQuery<T>(string sql)
{
return await Context.Ado.SqlQuerySingleAsync<T>(sql);
}
///
/// 查询返回 集合
///
///
///
/// 返回List 集合
public async Task<List<T>> SqlQuerys<T>(string sql)
{
return await Context.Ado.SqlQueryAsync<T>(sql);
}
///
/// ADO 查询
///
///
///
/// 返回List 集合
public async Task<List<T>> SqlQuery<T>(string sql, Dictionary<string, object> pairs)
{
return await Context.Ado.SqlQueryAsync<T>(sql, FormationParameter(pairs).ToArray());
}
///
/// ADO 查询
///
///
///
/// 返回List 集合
public async Task<List<TEntity>> SqlQuery(string sql, Dictionary<string, object> pairs)
{
return await Context.Ado.SqlQueryAsync<TEntity>(sql, FormationParameter(pairs).ToArray());
}
///
/// ADO 执行 增删改方法
///
///
///
public async Task<int> ExecuteCommand(string sql)
{
return await Context.Ado.ExecuteCommandAsync(sql);
}
///
/// ADO 执行 增删改方法
///
///
///
///
public async Task<int> ExecuteCommand(string sql, Dictionary<string, object> pairs)
{
return await Context.Ado.ExecuteCommandAsync(sql, FormationParameter(pairs).ToArray());
}
///
/// 获取序列自增ID
///
/// 序列名
/// 对应表名称
///
public long getquery_id(string sequenceName, string tableName)
{
long myvar = 0;
while (true)
{
string sql = "select " + sequenceName + ".NEXTVAL from dual ";
try
{
myvar = Context.Ado.SqlQuerySingle<long>(sql);
if (myvar > 0)
{
sql = "select count(*) from " + tableName + " where ID=" + myvar.ToString();
long myids = Context.Ado.SqlQuerySingle<long>(sql);
if (myids == 0)
{
break;
}
}
}
catch (Exception ex)
{
loggers.Error(new LogContent("getquery_id", "获取序列异常", $"【序列获取失败】:{ex.Message}"));
}
}
return myvar;
}
private List<SugarParameter> FormationParameter(Dictionary<string, object> pairs)
{
List<SugarParameter> olist = new List<SugarParameter>();
if (pairs.Count > 0)
{
foreach (var item in pairs.Keys)
{
olist.Add(new SugarParameter(item, pairs[item].ToString()));
}
}
return olist;
}
///
/// 执行包体 方法(存储过程)
///
/// imr_pkg_mr_data_syn.SP_SYN_SYS_USERS
///
public System.Data.DataTable ExecStoredProcedure(string packFuncName, List<SugarParameter> olist)
{
try
{
System.Data.DataTable pack = Context.Ado.UseStoredProcedure().GetDataTable(packFuncName, olist.ToArray());
return pack;
}
catch (Exception err)
{
throw err;
}
}
}
3、配置文件
{
"SqlSugarClient": [
{
"DbType": "3",
"Connection": "User Id=TEST;Password=123456;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Max Pool Size=512;Pooling=true",
"InitKeyType":"1"
}
],
"SqlSugarClient2": [
{
"DbType": "3",
"Connection": "User Id=TEST2;Password=123456;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Max Pool Size=512;Pooling=true",
"InitKeyType":"1"
}
]
}
4、自定义读取json 文件
public class Config
{
///
/// 数据库连接
///
public string ConnectionString { get; set; }
///
/// 数据库类型
///
public int DbType { get; set; }
///
/// 默认读取实体表方式
///
public int InitKeyType { get; set; }
///
/// 是否自动提交事务
///
public bool IsAutoCloseConnection { get; set; }
///
/// 获取ConnectionConfig
///
///
public static Config getBean(string connectName = "SqlSugarClient")
{
string path = "";
if (HttpContext.Current != null)
{
path = HttpContext.Current.Server.MapPath("/DbConfig.json");
}
else
{
path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "DbConfig.json");
}
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
JObject obj = JObject.Parse(json);
var jToken = obj[$"{connectName}"][0];
var conf = new Config()
{
DbType = Convert.ToInt32(jToken["DbType"]),
ConnectionString = jToken["Connection"].ToString(),
InitKeyType = Convert.ToInt32(jToken["InitKeyType"]),
IsAutoCloseConnection = true
};
return conf;
}
}
}
5、二级缓存类(SqlSugar官网提供)
///
/// 二级缓存
///
public class HttpRuntimeCache : ICacheService
{
public void Add<V>(string key, V value)
{
HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value);
}
public void Add<V>(string key, V value, int cacheDurationInSeconds)
{
HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value, cacheDurationInSeconds);
}
public bool ContainsKey<V>(string key)
{
return HttpRuntimeCacheHelper<V>.GetInstance().ContainsKey(key);
}
public V Get<V>(string key)
{
return HttpRuntimeCacheHelper<V>.GetInstance().Get(key);
}
public IEnumerable<string> GetAllKey<V>()
{
return HttpRuntimeCacheHelper<V>.GetInstance().GetAllKey();
}
public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
{
var cacheManager = HttpRuntimeCacheHelper<V>.GetInstance();
if (cacheManager.ContainsKey(cacheKey))
{
return cacheManager[cacheKey];
}
else
{
var result = create();
cacheManager.Add(cacheKey, result, cacheDurationInSeconds);
return result;
}
}
public void Remove<V>(string key)
{
HttpRuntimeCacheHelper<V>.GetInstance().Remove(key);
}
}
internal class HttpRuntimeCacheHelper<V>
{
#region 全局变量
private static HttpRuntimeCacheHelper<V> _instance = null;
private static readonly object _instanceLock = new object();
#endregion
#region 构造函数
private HttpRuntimeCacheHelper() { }
#endregion
#region 属性
///
///根据key获取value
///
///
public V this[string key]
{
get { return (V)HttpRuntime.Cache[CreateKey(key)]; }
}
#endregion
#region 公共函数
///
/// key是否存在
///
/// key
/// /// 存在true 不存在false . /// ///
public bool ContainsKey(string key)
{
return HttpRuntime.Cache[CreateKey(key)] != null;
}
///
/// 获取缓存值
///
/// key
///
public V Get(string key)
{
return (V)HttpRuntime.Cache.Get(CreateKey(key));
}
///
/// 获取实例 (单例模式)
///
///
public static HttpRuntimeCacheHelper<V> GetInstance()
{
if (_instance == null)
lock (_instanceLock)
if (_instance == null)
_instance = new HttpRuntimeCacheHelper<V>();
return _instance;
}
///
/// 插入缓存(默认20分钟)
///
/// key
/// value
public void Add(string key, V value)
{
Add(key, value, 60 * 20);
}
///
/// 插入缓存
///
/// key
/// value
/// 过期时间单位秒
public void Add(string key, V value, int cacheDurationInSeconds)
{
Add(key, value, cacheDurationInSeconds, CacheItemPriority.Default);
}
///
/// 插入缓存.
///
/// key
/// value
/// 过期时间单位秒
/// 缓存项属性
public void Add(string key, V value, int cacheDurationInSeconds, CacheItemPriority priority)
{
string keyString = CreateKey(key);
HttpRuntime.Cache.Insert(keyString, value, null,
DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
}
///
/// 插入缓存.
///
/// key
/// value
/// 过期时间单位秒
/// 缓存项属性
public void Add(string key, V value, int
cacheDurationInSeconds, CacheDependency dependency, CacheItemPriority priority)
{
string keyString = CreateKey(key);
HttpRuntime.Cache.Insert(keyString, value,
dependency, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
}
///
/// 删除缓存
///
/// key
public void Remove(string key)
{
HttpRuntime.Cache.Remove(CreateKey(key));
}
///
/// 清除所有缓存
///
public void RemoveAll()
{
System.Web.Caching.Cache cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
ArrayList al = new ArrayList();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}
foreach (string key in al)
{
cache.Remove(key);
}
}
///
/// 清除所有包含关键字的缓存
///
/// 关键字
public void RemoveAll(Func<string, bool> removeExpression)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
var allKeyList = GetAllKey();
var delKeyList = allKeyList.Where(removeExpression).ToList();
foreach (var key in delKeyList)
{
HttpRuntime.Cache.Remove(key); ;
}
}
///
/// 获取所有缓存key
///
///
public IEnumerable<string> GetAllKey()
{
IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
yield return CacheEnum.Key.ToString();
}
}
#endregion
#region 私有函数
///
///创建KEY
///
/// Key
///
private string CreateKey(string key)
{
return key;
}
#endregion
}