using JinYuan.DAL.Enums;
using JinYuan.DAL.Models;
using JinYuan.Helper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace JinYuan.DAL
{
public class SQLSugarService : ISugarHelper
{
private ISqlSugarClient _db;
// 实现属性
//public ISqlSugarClient DbClient => _db;
public ISqlSugarClient Db => SqlSugarDb;
// 兼容你原来的代码,可保留
//public ISqlSugarClient DbClient => SqlSugarDb;
public void SetConnectionStr(string connectionStr, SqlSugar.DbType dbType)
{
SQLSugarHelper.connString = connectionStr;
SQLSugarHelper.dbType = dbType;
SqlSugarDb = SQLSugarHelper.SqlSugarClient;
}
///
/// 数据库连接对象
///
public SqlSugarScope SqlSugarDb { get; set; }
#region 数据库管理
///
/// 添加列
///
/// 表名
/// 列信息
/// 值
public bool AddColumn(string tableName, DbColumnInfo column)
{
return SqlSugarDb.DbMaintenance.AddColumn(tableName, column);
}
///
/// 添加主键
///
/// 表名
/// 列名
/// 值
public bool AddPrimaryKey(string tableName, string columnName)
{
return SqlSugarDb.DbMaintenance.AddPrimaryKey(tableName, columnName);
}
///
/// 备份数据库
///
/// 数据库名
/// 文件名
/// 值
public bool BackupDataBase(string databaseName, string fullFileName)
{
return SqlSugarDb.DbMaintenance.BackupDataBase(databaseName, fullFileName);
}
///
/// 备份表
///
/// 旧表名
/// 行表名
/// 行数
/// 值
public bool BackupTable(string oldTableName, string newTableName, int maxBackupDataRows = int.MaxValue)
{
return SqlSugarDb.DbMaintenance.BackupTable(oldTableName, newTableName, maxBackupDataRows);
}
///
/// 创建表
///
/// 表名
/// 列集合
/// 是否创建主键
/// 值
public bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true)
{
return SqlSugarDb.DbMaintenance.CreateTable(tableName, columns, isCreatePrimaryKey);
}
///
/// 删除列
///
/// 表名
/// 列名
/// 值
public bool DropColumn(string tableName, string columnName)
{
return SqlSugarDb.DbMaintenance.DropColumn(tableName, columnName);
}
///
/// 删除约束
///
/// 表名
/// 约束名
/// 值
public bool DropConstraint(string tableName, string constraintName)
{
return SqlSugarDb.DbMaintenance.DropConstraint(tableName, constraintName);
}
///
/// 删除表
///
///
/// 值
public bool DropTable(string tableName)
{
return SqlSugarDb.DbMaintenance.DropTable(tableName);
}
///
/// 获取列信息
///
/// 表名
/// 是否缓存
/// 值
public List GetColumnInfosByTableName(string tableName, bool isCache = true)
{
return SqlSugarDb.DbMaintenance.GetColumnInfosByTableName(tableName, isCache);
}
///
/// 获取自增列
///
/// 表名
/// 值
public List GetIsIdentities(string tableName)
{
return SqlSugarDb.DbMaintenance.GetIsIdentities(tableName);
}
///
/// 获取主键
///
/// 表名
/// 值
public List GetPrimaries(string tableName)
{
return SqlSugarDb.DbMaintenance.GetPrimaries(tableName);
}
///
/// 获取表集合
///
/// 是否缓存
/// 值
public List GetTableInfoList(bool isCache = true)
{
return SqlSugarDb.DbMaintenance.GetTableInfoList(isCache);
}
///
/// 获取视图集合
///
/// 是否缓存
/// 值
public List GetViewInfoList(bool isCache = true)
{
return SqlSugarDb.DbMaintenance.GetViewInfoList(isCache);
}
///
/// 检测列是否存在
///
/// 表名
/// 列名
/// 值
public bool IsAnyColumn(string tableName, string column)
{
return SqlSugarDb.DbMaintenance.IsAnyColumn(tableName, column);
}
///
/// 检测约束
///
/// 约束名称
/// 值
public bool IsAnyConstraint(string constraintName)
{
return SqlSugarDb.DbMaintenance.IsAnyConstraint(constraintName);
}
///
/// 检测是否有任何系统表权限
///
/// 值
public bool IsAnySystemTablePermissions()
{
return SqlSugarDb.DbMaintenance.IsAnySystemTablePermissions();
}
///
/// 检测表是否存在
///
/// 表名
/// 是否缓存
/// 值
public bool IsAnyTable(string tableName, bool isCache = true)
{
return SqlSugarDb.DbMaintenance.IsAnyTable(tableName, isCache);
}
///
/// 检测列是否自增列
///
/// 表名
/// 列名
/// 值
public bool IsIdentity(string tableName, string column)
{
return SqlSugarDb.DbMaintenance.IsIdentity(tableName, column);
}
///
/// 检测列是否主键
///
/// 表名
/// 列名
/// 值
public bool IsPrimaryKey(string tableName, string column)
{
return SqlSugarDb.DbMaintenance.IsPrimaryKey(tableName, column);
}
///
/// 重置列名
///
/// 表名
/// 旧列名
/// 新列名
/// 值
public bool RenameColumn(string tableName, string oldColumnName, string newColumnName)
{
return SqlSugarDb.DbMaintenance.RenameColumn(tableName, oldColumnName, newColumnName);
}
///
/// 重置表数据
///
/// 表名
/// 值
public bool TruncateTable(string tableName)
{
return SqlSugarDb.DbMaintenance.TruncateTable(tableName);
}
///
/// 修改列信息
///
/// 表名
/// 列信息
/// 值
public bool UpdateColumn(string tableName, DbColumnInfo column)
{
return SqlSugarDb.DbMaintenance.UpdateColumn(tableName, column);
}
///
/// 获取数据库时间
///
/// 返回值
public DateTime GetDataBaseTime()
{
return SqlSugarDb.GetDate();
}
#endregion
#region 查询
///
/// 查询所有
///
///
///
///
public List QueryAll() where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.UpdLock);
return up.ToList();
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 查询-返回自定义数据
///
/// 泛型参数(集合成员的类型)
/// 返回值类型
/// 返回值表达式
/// 查询表达式
/// 值
public TResult QuerySelect(Expression> expression, Expression> whereLambda = null) where T : class, new()
{
try
{
var datas = SqlSugarDb.Queryable().With(SqlWith.NoLock).Where(whereLambda).Select(expression).First();
return datas;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 查询-返回自定义数据
///
/// 泛型参数(集合成员的类型)
/// 返回值类型
/// 返回值表达式
/// 查询表达式
/// 值
public List QuerySelectList(Expression> expression, Expression> whereLambda = null) where T : class, new()
{
try
{
var datas = SqlSugarDb.Queryable().With(SqlWith.NoLock).Where(whereLambda).Select(expression).ToList();
return datas;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 查询单条数据
///
/// 泛型参数(集合成员的类型)
/// 查询表达式
/// 值
public T Query(Expression> whereLambda = null) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
return up.First();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 异步查询单条数据
///
/// 泛型参数(集合成员的类型)
/// 查询表达式
///
///
public Task QueryAsync(Expression> whereLambda = null) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
return up.FirstAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 根据条件查询排序数据
///
///
///
///
///
public T Query(Expression> whereLambda2 = null, Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (whereLambda2 != null)
{
up = up.Where(whereLambda2);
}
if (whereLambda != null)
{
up = up.OrderBy(whereLambda, byType);
}
return up.First();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public T Query(QueryDescriptor query = null) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (query != null)
{
if (query.Conditions != null)
{
var conds = ParseCondition(query.Conditions);
up = up.Where(conds);
}
if (query.OrderBys != null)
{
var orderBys = ParseOrderBy(query.OrderBys);
up = up.OrderBy(orderBys);
}
}
return up.First();
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 查询集合
///
/// 泛型参数(集合成员的类型)
/// 过滤条件
/// 实体
public List QueryWhereList(Expression> whereLambda = null) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.UpdLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
return up.ToList();
}
catch (Exception ex)
{
LogHelper.Instance.WriteError($"查询集合异常:{ex}", "SysErrorLog");
return null;
//throw new Exception(ex.Message);
}
}
public async Task> QueryWhereListAsync(Expression> whereLambda = null) where T : class, new()
{
try
{
var up = SqlSugarDb.Queryable().With(SqlWith.UpdLock);
if (whereLambda != null)
up = up.Where(whereLambda);
return await up.ToListAsync();
}
catch
{
return new List();
}
}
///
/// 查询集合
///
/// 泛型参数(集合成员的类型)
/// 过滤条件
/// 实体
public List QueryList(QueryDescriptor query = null) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (query != null)
{
if (query.Conditions != null)
{
var conds = ParseCondition(query.Conditions);
up = up.Where(conds);
}
if (query.OrderBys != null)
{
var orderBys = ParseOrderBy(query.OrderBys);
up = up.OrderBy(orderBys);
}
}
return up.ToList();
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 查询前N条数据
///
///
///
///
///
///
///
public List QueryList(string sort, int Take, Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
if (sort != "")
{
var orderBys = ParseOrderBy(sort, byType);
up = up.OrderBy(orderBys).Take(Take);
}
return up.ToList();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 异步查询前N条数据
///
///
///
///
///
///
///
///
public async Task> QueryListAsync(string sort, int Take, Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.CopyNew().Queryable().With(SqlWith.NoLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
if (sort != "")
{
var orderBys = ParseOrderBy(sort, byType);
up = up.OrderBy(orderBys).Take(Take);
}
return await up.ToListAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 查询列表数据,根据字段排序排列
///
///
///
///
///
///
///
public List QueryList(string sort = "", Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
if (sort != "")
{
var orderBys = ParseOrderBy(sort, byType);
up = up.OrderBy(orderBys);
}
return up.ToList();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 异步根据字段查询排列
///
///
///
///
///
///
public async Task> QueryListAsync(string sort = "", Expression> whereLambda = null, OrderByType byType = OrderByType.Desc) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.CopyNew().Queryable().With(SqlWith.NoLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
if (sort != "")
{
var orderBys = ParseOrderBy(sort, byType);
up = up.OrderBy(orderBys);
}
return await up.ToListAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 排序转换
///
///
///
///
private string ParseOrderBy(string sort, OrderByType order)
{
var conds = "";
switch (order)
{
case OrderByType.Asc:
conds += $"{sort} asc,";
break;
case OrderByType.Desc:
conds += $"{sort} desc,";
break;
default:
throw new ArgumentOutOfRangeException();
}
return conds.TrimEnd(',');
}
///
/// 查询集合
///
/// 泛型参数(集合成员的类型)
/// sql
/// 实体
public List QuerySqlList(string sql) where T : class, new()
{
try
{
return SqlSugarDb.SqlQueryable(sql).ToList();
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 异步查询集合-多值
///
///
///
///
///
public async Task> QuerySqlListAsync(string sql) where T : class, new()
{
try
{
return await SqlSugarDb.CopyNew().SqlQueryable(sql).ToListAsync();
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 分页查询
///
/// 泛型参数(集合成员的类型)
/// 过滤条件
/// 总行数
/// 实体
public List QueryPageList(QueryDescriptor query, out int totalCount) where T : class, new()
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
var listDatas = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (query.Conditions != null)
{
var conds = ParseCondition(query.Conditions);
listDatas = listDatas.Where(conds);
}
if (query.OrderBys != null)
{
var orderBys = ParseOrderBy(query.OrderBys);
listDatas = listDatas.OrderBy(orderBys);
}
totalCount = 0;
if (query.PageSize == 0)
{
var datas = listDatas.ToList();
totalCount = datas.Count;
return datas;
}
else
{
var datas = listDatas.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
return datas;
}
}
///
/// 查询集合-多值
///
/// 泛型参数(集合成员的类型)
/// 字段名
/// 数据集合
/// 值
public List In(string inFieldName, List inValues) where T : class, new()
{
try
{
return SqlSugarDb.Queryable().With(SqlWith.NoLock).In(inFieldName, inValues).ToList();
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 查询集合-通过多值(主键)
///
/// 泛型参数(集合成员的类型)
/// 主键数据集合
/// 值
public List In(List values) where T : class, new()
{
return SqlSugarDb.Queryable().With(SqlWith.NoLock).In(values).ToList();
}
///
/// 查询集合
///
/// 泛型参数(集合成员的类型)
/// 查询表达式
/// 实体
public DataTable QueryDataTable(Expression> whereLambda = null) where T : class, new()
{
try
{
ISugarQueryable up = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (whereLambda != null)
{
up = up.Where(whereLambda);
}
return up.ToDataTable();
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 查询集合
///
/// sql
/// 实体
public DataTable QueryDataTable(string sql)
{
try
{
return SqlSugarDb.Ado.GetDataTable(sql);
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 查询单个值
///
/// sql
/// 单个值
public object QuerySqlScalar(string sql)
{
try
{
return SqlSugarDb.Ado.GetScalar(sql);
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
///
/// 分页查询
///
/// 泛型参数(集合成员的类型)
/// 过滤条件
/// 总行数
/// DataTable
public DataTable QueryDataTablePageList(QueryDescriptor query, out int totalCount) where T : class, new()
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
var listDatas = SqlSugarDb.Queryable().With(SqlWith.NoLock);
if (query.Conditions != null)
{
var conds = ParseCondition(query.Conditions);
listDatas = listDatas.Where(conds);
}
if (query.OrderBys != null)
{
var orderBys = ParseOrderBy(query.OrderBys);
listDatas = listDatas.OrderBy(orderBys);
}
totalCount = 0;
var datas = listDatas.ToDataTablePage(query.PageIndex, query.PageSize, ref totalCount);
return datas;
}
#endregion
#region 新增
///
/// 新增
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 操作影响的行数
public int Add(T entity) where T : class, new()
{
try
{
var result = SqlSugarDb.Insertable(entity).ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 新增
///
/// 泛型参数(集合成员的类型)
/// 泛型集合
/// 操作影响的行数
public int Add(List entitys) where T : class, new()
{
try
{
if (entitys.Count == 0) return 1;
var result = SqlSugarDb.Insertable(entitys).ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 新增
///
/// 泛型参数(集合成员的类型)
/// 字典集合(Key:列名 Value:值)
/// 操作影响的行数
public int Add(Dictionary keyValues) where T : class, new()
{
try
{
var result = SqlSugarDb.Insertable(keyValues).ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 新增
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 返回实体
public T AddReturnEntity(T entity) where T : class, new()
{
try
{
var result = SqlSugarDb.Insertable(entity).ExecuteReturnEntity();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 新增
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 返回自增列
public int AddReturnIdentity(T entity) where T : class, new()
{
try
{
var result = SqlSugarDb.Insertable(entity).ExecuteReturnIdentity();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 新增
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 返回bool
public bool AddReturnBool(T entity) where T : class, new()
{
try
{
var result = SqlSugarDb.Insertable(entity).With(SqlWith.UpdLock).ExecuteCommand() > 0;
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task AddReturnBoolAsync(T entity) where T : class, new()
{
try
{
var result = await SqlSugarDb.Insertable(entity).With(SqlWith.UpdLock).ExecuteCommandAsync() > 0;
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 新增
///
/// 泛型参数(集合成员的类型)
/// 泛型集合
/// 返回bool
public bool AddReturnBool(List entitys) where T : class, new()
{
try
{
if (entitys.Count == 0) return true;
var result = SqlSugarDb.Insertable(entitys).ExecuteCommand() > 0;
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task AddReturnBoolAsync(List entitys) where T : class, new()
{
try
{
if (entitys == null || entitys.Count == 0) return true;
var count = await SqlSugarDb.Insertable(entitys).ExecuteCommandAsync();
return count > 0;
//var result = await SqlSugarDb.Insertable(entitys).With(SqlWith.UpdLock).ExecuteCommandAsync() > 0;
//return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region 修改
///
/// 修改(主键是更新条件)
///
/// 泛型参数(集合成员的类型)
/// 实体对象(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件
/// 不更新的列
/// 是否加锁
/// 操作影响的行数
///
public int Update(T entity, List lstIgnoreColumns = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable(entity);
if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
{
up = up.IgnoreColumns(false);
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 修改(主键是更新条件)
///
/// 泛型参数(集合成员的类型)
/// 实体对象集合(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件
/// 不更新的列
/// 是否加锁
/// 操作影响的行数
public int Update(List entitys, List lstIgnoreColumns = null, bool isLock = true) where T : class, new()
{
try
{
if (entitys.Count == 0) return 1;
IUpdateable up = SqlSugarDb.Updateable(entitys);
if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
{
up = up.IgnoreColumns(lstIgnoreColumns.Contains(lstIgnoreColumns.First()));
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 修改
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 条件
/// 不更新的列
/// 是否加锁
/// 操作影响的行数
public int Update(T entity, Expression> where, List lstIgnoreColumns = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable(entity);
if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
{
up = up.IgnoreColumns(lstIgnoreColumns.Contains(lstIgnoreColumns.First()));
}
up = up.Where(where);
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 修改
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 条件
/// 是否加锁
/// 操作影响的行数
public int Update(Expression> update, Expression> where = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable().UpdateColumns(update);
if (where != null)
{
up = up.Where(where);
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 修改加1
///
///
///
///
///
///
public int Update(Expression> update, Expression> where = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable().SetColumns(update);
if (where != null)
{
up = up.Where(where);
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
///异步修改加1
///
///
///
///
///
///
///
public async Task UpdateAsync(Expression> update, Expression> where = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable().SetColumns(update);
if (where != null)
{
up = up.Where(where);
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = await up.ExecuteCommandAsync();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public async Task UpdateAsync(List entitys, List lstIgnoreColumns = null, bool isLock = true) where T : class, new()
{
if (entitys == null || entitys.Count == 0) return 0;
var up = SqlSugarDb.Updateable(entitys);
if (lstIgnoreColumns != null && lstIgnoreColumns.Any())
up = up.IgnoreColumns(lstIgnoreColumns.First());
if (isLock)
up = up.With(SqlWith.UpdLock);
return await up.ExecuteCommandAsync();
}
///
/// 修改单条数据
///
///
/// 实体类
/// 指定更新行
/// 更新表达式
/// 是否加锁
///
///
public int UpdateSingle(T entity, Expression> IgnoreColumns = null, Expression> where = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable(entity);
if (IgnoreColumns != null)
{
up = up.UpdateColumns(IgnoreColumns);
}
if (where != null)
{
up = up.Where(where);
}
var result = up.ExecuteCommand();
return result;
//SqlSugarDb.Updateable(new T ()
//{
// Id = entity.Id,
// EmailArr = "test@test.com",
// EmailContent = "测试邮件,请忽略111"
//}).UpdateColumns(it => new { it.EmailArr, it.EmailContent }).ExecuteCommandAsync();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 异步更新
///
///
///
///
///
///
///
///
public async Task UpdateSingleAsync(T entity, Expression> IgnoreColumns = null, Expression> where = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable(entity);
if (IgnoreColumns != null)
{
up = up.UpdateColumns(IgnoreColumns);
}
if (where != null)
{
up = up.Where(where);
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = await up.ExecuteCommandAsync();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 修改
///
/// 泛型参数(集合成员的类型)
/// 字典集合(Key:列名 Value:值)
/// 条件
/// 是否加锁
/// 操作影响的行数
public int Update(Dictionary keyValues, Expression> where = null, bool isLock = true) where T : class, new()
{
try
{
IUpdateable up = SqlSugarDb.Updateable(keyValues);
if (where != null)
{
up = up.Where(where);
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 批量修改需要更新的列
///
/// 泛型参数(集合成员的类型)
/// 实体对象(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件
/// 更新指定列
/// 条件(为空则以主键更新,反之需要把wherecolumns中的列加到UpdateColumns中)
/// 是否加锁
/// 操作影响的行数
public int UpdateColumns(List entitys, Expression> updateColumns, Expression> wherecolumns = null, bool isLock = true) where T : class, new()
{
try
{
if (entitys.Count == 0) return 1;
IUpdateable up = SqlSugarDb.Updateable(entitys).UpdateColumns(updateColumns);
if (wherecolumns != null)
{
up = up.WhereColumns(wherecolumns);
}
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 修改 通过RowVer及主键Code 更新
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 不更新的列
/// 是否加锁
/// 操作影响的行数
public int UpdateRowVer(T entity, List lstIgnoreColumns = null, bool isLock = true) where T : class, new()
{
try
{
Type ts = entity.GetType();
var rowVerProperty = ts.GetProperty("RowVer");
if (rowVerProperty == null)
{
throw new Exception("Column RowVer Not Exist");
}
if (rowVerProperty.GetValue(entity, null) == null)
{
throw new Exception("RowVer Value Is Null");
}
var codeProperty = ts.GetProperty("Code");
if (codeProperty == null)
{
throw new Exception("Column Code Not Exist");
}
if (codeProperty.GetValue(entity, null) == null)
{
throw new Exception("Code Value Is Null");
}
var rowVerValue = int.Parse(rowVerProperty.GetValue(entity, null).ToString());
var codeValue = codeProperty.GetValue(entity, null).ToString();
var sqlWhere = $" RowVer={rowVerValue} AND Code='{codeValue}'";
rowVerProperty.SetValue(entity, rowVerValue + 1, null);
IUpdateable up = SqlSugarDb.Updateable(entity);
if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
{
up = up.IgnoreColumns(lstIgnoreColumns.Contains(lstIgnoreColumns.First()));
}
up = up.Where(sqlWhere);
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//表达式写2列更新2列,其他不会更新
///
/// 修改
///
/// 泛型参数(集合成员的类型)
/// 实体对象
/// 更新条件
/// 是否加锁
/// 操作影响的行数
public int UpdateRowVer(Expression> update, Dictionary where, bool isLock = true) where T : class, new()
{
try
{
if (!where.ContainsKey("RowVer"))
{
throw new Exception("Column RowVer Not Exist");
}
if (where["RowVer"] == null)
{
throw new Exception("RowVer Value Is Null");
}
if (update.Body.ToString().IndexOf("RowVer", StringComparison.Ordinal) == -1)
{
throw new Exception("Column RowVer Update Is Null");
}
var sqlWhere = "";
foreach (var item in where)
{
sqlWhere += string.IsNullOrWhiteSpace(sqlWhere) ? $" {item.Key}='{item.Value}'" : $" and {item.Key}='{item.Value}'";
}
IUpdateable up = SqlSugarDb.Updateable().UpdateColumns(update).Where(sqlWhere);
if (isLock)
{
up = up.With(SqlWith.UpdLock);
}
var result = up.ExecuteCommand();
return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region 删除
///
/// 初始化表
///
///
///
public void Delete() where T : class, new()
{
try
{
SqlSugarDb.DbMaintenance.TruncateTable();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// 删除
///
/// 泛型参数(集合成员的类型)
/// 主键值
/// 是否加锁
/// 操作影响的行数
public int DeleteByPrimary(List