SqlSugar 封装.Net Core和.Net 二个版本

自己做项目的时候封装的SqlSugar操作类,备份以后用…
简介:
SqlSugar :是一款高性能(达到ADO.NET最高性能水平)
SqlSugar :是除EF外拉姆达解析最完善的ORM,多表 、UnionALL、 交叉子查询、真实的批量操作和分页
SqlSugar :用法简单,功能齐全
SqlSugar :对数据库结构没太多要求支持多主键、多自增列、支持异步
SqlSugar :支持分布式二级缓存(CRUD可以自动清除缓存)和支持读写分离功能大型项目必备
SqlSugar支持.Net 4.0+ 和 .Net Core
官网:http://www.codeisbug.com

**
源码分享个大家.Net Core和.Net 二个版本
**
提取码:最下面

#region << 版 本 注 释 >>
/*---------------------------------------------------------------- 
* 类 名 称 :OrderByClause
* 类 描 述 :    
* 作    者 :xnlzg
* 创建时间 :2018/11/7 14:12:53
* 更新时间 :2018/11/7 14:12:53
* 说    明 :
* 版 本 号 :v1.0.0.0
*******************************************************************
* Copyright @ xnlzg 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

namespace XN.Common
{
    /// 
    /// 排序实体
    /// 
    public class OrderByClause
    {
        /// 
        /// 排序字段
        /// 
        public string Sort { get; set; }
        /// 
        /// 排序类型
        /// 
        public OrderSequence Order { get; set; }
    }
}
#region << 版 本 注 释 >>
/*---------------------------------------------------------------- 
* 类 名 称 :OrderSequence
* 类 描 述 :    
* 作    者 :xnlzg
* 创建时间 :2018/11/7 14:12:32
* 更新时间 :2018/11/7 14:12:32
* 说    明 :
* 版 本 号 :v1.0.0.0
*******************************************************************
* Copyright @ xnlzg 2018. All rights reserved5wbk.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

namespace XN.Common
{
    /// 
    /// 排序枚举
    /// 
    public enum OrderSequence
    {
        /// 
        /// 正序
        /// 
        Asc,
        /// 
        /// 倒序
        /// 
        Desc
    }
}

#region << 版 本 注 释 >>
/*---------------------------------------------------------------- 
* 类 名 称 :QueryCondition
* 类 描 述 :    
* 作    者 :xnlzg
* 创建时间 :2018/11/7 14:14:29
* 更新时间 :2018/11/7 14:14:29
* 说    明 :
* 版 本 号 :v1.0.0.0
*******************************************************************
* Copyright @ xnlzg 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

namespace XN.Common
{
    /// 
    /// 查询
    /// 
    public class QueryCondition
    {
        /// 
        /// 字段名称
        /// 
        public string Key { get; set; }
        /// 
        /// 查询操作
        /// 
        public QueryOperator Operator { get; set; }
        /// 
        /// 值
        /// 
        public object Value { get; set; }

    }
}

#region << 版 本 注 释 >>
/*---------------------------------------------------------------- 
* 类 名 称 :QueryDescriptor
* 类 描 述 :    
* 作    者 :xnlzg
* 创建时间 :2018/11/7 14:15:04
* 更新时间 :2018/11/7 14:15:04
* 说    明 :
* 版 本 号 :v1.0.0.0
*******************************************************************
* Copyright @ xnlzg 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

using System.Collections.Generic;

namespace XN.Common
{
    /// 
    /// 查询集合
    /// 
    public class QueryDescriptor
    {
        /// 
        /// 行数
        /// 
        public int PageSize { get; set; }
        /// 
        /// 页码
        /// 
        public int PageIndex { get; set; }
        /// 
        /// 排序
        /// 
        public List OrderBys { get; set; }
        /// 
        /// 条件
        /// 
        public List Conditions { get; set; }
    }
}

#region << 版 本 注 释 >>
/*---------------------------------------------------------------- 
* 类 名 称 :QueryOperator
* 类 描 述 :    
* 作    者 :xnlzg
* 创建时间 :2018/11/7 14:14:03
* 更新时间 :2018/11/7 14:14:03
* 说    明 :
* 版 本 号 :v1.0.0.0
*******************************************************************
* Copyright @ xnlzg 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion 
namespace XN.Common
{
    /// 
    /// 查询条件枚举
    /// 
    public enum QueryOperator
    {
        /// 
        /// 相等
        /// 
        Equal,
        /// 
        /// 匹配
        /// 
        Like,
        /// 
        /// 大于
        /// 
        GreaterThan,
        /// 
        /// 大于或等于
        /// 
        GreaterThanOrEqual,
        /// 
        /// 小于
        /// 
        LessThan,
        /// 
        /// 小于或等于
        /// 
        LessThanOrEqual,
        /// 
        /// 等于集合
        /// 
        In,
        /// 
        /// 不等于集合
        /// 
        NotIn,
        /// 
        /// 左边匹配
        /// 
        LikeLeft,
        /// 
        /// 右边匹配
        /// 
        LikeRight,
        /// 
        /// 不相等
        /// 
        NoEqual,
        /// 
        /// 为空或空
        /// 
        IsNullOrEmpty,
        /// 
        /// 不为空
        /// 
        IsNot,
        /// 
        /// 不匹配
        /// 
        NoLike,
        /// 
        /// 时间段 值用 "|" 隔开
        /// 
        DateRange
    }
}

#region 开发单位:xnlzg 版权所有Copyright (C) 2011
/***-------------------------------------------------------------------------------------
		命名空间:OPPO.DBUtility.Sugar
		文 件 名:BaseDbContext
		创建时间:2018/6/8 10:15:10
		创 建 人:xnlzg 
		修改时间:
		修 改 人:
		说    明:			 
-------------------------------------------------------------------------------------***/
#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using SqlSugar;

namespace XN.Common
{
    /// 
    /// 数据库操作类
    /// 
    public class BaseDbContext
    {

        /// 
        /// 注意当前方法的类不能是静态的 public static class这么写是错误的
        /// 
        public static SqlSugarClient Db
        {
            get
            {
                var connMain = ConfigurationManager.ConnectionStrings["ConnMain"];
                var connFrom = ConfigurationManager.ConnectionStrings["ConnFrom"];
                return InitDataBase(connFrom == null
                    ? new List { connMain.ToString() }
                    : new List { connMain.ToString(), connFrom.ToString() });
            }
        }


        /// 
        ///  获得SqlSugarClient
        /// 
        /// 服务器IP或文件路径
        /// 用户名
        /// 密码
        /// 数据库
        public static SqlSugarClient GetIntance(string serverIp, string user, string pass, string dataBase)
        {
            var listConn = new List();
            switch ((DbType)ConfigurationManager.ConnectionStrings["DbType"].ObjToInt())
            {
                case DbType.SqlServer:
                    listConn.Add($"server={serverIp};user id={user};password={pass};persistsecurityinfo=True;database={dataBase}");
                    break;
                case DbType.MySql:
                    listConn.Add($"Server={serverIp};Database={dataBase};Uid={user};Pwd={pass};");
                    break;
                case DbType.Oracle:
                    listConn.Add($"Server=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={serverIp})(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={dataBase})));User Id={user};Password={pass};Persist Security Info=True;Enlist=true;Max Pool Size=300;Min Pool Size=0;Connection Lifetime=300");
                    break;
                case DbType.PostgreSQL:
                    listConn.Add($"PORT=5432;DATABASE={dataBase};HOST={serverIp};PASSWORD={pass};USER ID={user}");
                    break;
                case DbType.Sqlite:
                    listConn.Add($"Data Source={serverIp};Version=3;Password={pass};");
                    break;
            }
            return InitDataBase(listConn);
        }
        /// 
        /// 初始化数据库连接
        /// 
        /// 连接字符串
        private static SqlSugarClient InitDataBase(List listConn)
        {
            var connStr = "";//主库
            var slaveConnectionConfigs = new List();//从库集合
            for (var i = 0; i < listConn.Count; i++)
            {
                if (i == 0)
                {
                    connStr = listConn[i];//主数据库连接
                }
                else
                {
                    slaveConnectionConfigs.Add(new SlaveConnectionConfig()
                    {
                        HitRate = i * 2,
                        ConnectionString = listConn[i]
                    });
                }
            }

            //如果配置了 SlaveConnectionConfigs那就是主从模式,所有的写入删除更新都走主库,查询走从库,
            //事务内都走主库,HitRate表示权重 值越大执行的次数越高,如果想停掉哪个连接可以把HitRate设为0 
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connStr,
                DbType = (DbType)ConfigurationManager.ConnectionStrings["DbType"].ObjToInt(),
                IsAutoCloseConnection = true,
                SlaveConnectionConfigs = slaveConnectionConfigs,
                IsShardSameThread = true
            });
            db.Ado.CommandTimeOut = 30000;//设置超时时间
            db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
            {
                //LogHelper.WriteLog($"执行时间:{db.Ado.SqlExecutionTime.TotalMilliseconds}毫秒 \r\nSQL如下:{sql} \r\n参数:{GetParams(pars)} ", "SQL执行");
            };
            db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
            {
                if (db.TempItems == null) db.TempItems = new Dictionary();
            };
            db.Aop.OnError = (exp) =>//执行SQL 错误事件
            {
                //LogHelper.WriteLog($"SQL错误:{exp.Message}\r\nSQL如下:{exp.Sql}", "SQL执行");
                throw new Exception(exp.Message);
            };
            db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL执行前 可以修改SQL
            {
                return new KeyValuePair(sql, pars);
            };
            db.Aop.OnDiffLogEvent = (it) => //可以方便拿到 数据库操作前和操作后的数据变化。
            {
                //var editBeforeData = it.BeforeData;
                //var editAfterData = it.AfterData;
                //var sql = it.Sql;
                //var parameter = it.Parameters;
                //var data = it.BusinessData;
                //var time = it.Time;
                //var diffType = it.DiffType;//枚举值 insert 、update 和 delete 用来作业务区分

                //你可以在这里面写日志方法
            };
            return db;
        }
        /// 
        /// 获取参数信息
        /// 
        /// 
        /// 
        private static string GetParams(SugarParameter[] pars)
        {
            return pars.Aggregate("", (current, p) => current + $"{p.ParameterName}:{p.Value}, ");
        }
    }
}

#region << 版 本 注 释 >>
/*---------------------------------------------------------------- 
* 类 名 称 :ISqlRepository
* 类 描 述 :    
* 作    者 :xnlzg
* 创建时间 :2018/7/23 15:56:57
* 更新时间 :2018/7/23 15:56:57
* 说    明 :
* 版 本 号 :v1.0.0.0
*******************************************************************
* Copyright @ xnlzg 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq.Expressions;
using SqlSugar;
using XN.Common;

namespace OPPO.DBUtility
{
    /// 
    /// SqlSugar操作接口类
    /// 
    public interface ISugerHandler : IDisposable
    {

        #region 事务

        /// 
        /// 事务操作
        /// 注意:代码段里面如果调用本身类其它方法或其它类方法必须带着var db = SugerHandler.Instance()这个db走,不带着走事务回滚会不成功
        ///  
        /// 代码段 
        /// 事务级别
        void InvokeTransactionScope(Action serviceAction, IsolationLevel level = IsolationLevel.ReadCommitted);
        #endregion

        #region 数据库管理
        /// 
        /// 添加列
        /// 
        /// 表名
        /// 列信息
        /// 
        bool AddColumn(string tableName, DbColumnInfo column);
        /// 
        /// 添加主键
        /// 
        /// 表名
        /// 列名
        /// 
        bool AddPrimaryKey(string tableName, string columnName);
        /// 
        /// 备份数据库
        /// 
        /// 数据库名
        /// 文件名
        /// 
        bool BackupDataBase(string databaseName, string fullFileName);
        /// 
        /// 备份表
        /// 
        /// 旧表名
        /// 行表名
        /// 行数
        /// 
        bool BackupTable(string oldTableName, string newTableName, int maxBackupDataRows = int.MaxValue);
        /// 
        /// 创建表
        /// 
        /// 表名
        /// 列集合
        /// 是否创建主键
        /// 
        bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true);
        /// 
        /// 删除列
        /// 
        /// 表名
        /// 列名
        /// 
        bool DropColumn(string tableName, string columnName);
        /// 
        /// 删除约束
        /// 
        /// 表名
        /// 约束名
        /// 
        bool DropConstraint(string tableName, string constraintName);
        /// 
        /// 删除表
        /// 
        /// 
        /// 
        bool DropTable(string tableName);
        /// 
        /// 获取列信息
        /// 
        /// 表名
        /// 是否缓存
        /// 
        List GetColumnInfosByTableName(string tableName, bool isCache = true);
        /// 
        /// 获取自增列
        /// 
        /// 表名
        /// 
        List GetIsIdentities(string tableName);
        /// 
        /// 获取主键
        /// 
        /// 表名
        /// 
        List GetPrimaries(string tableName);
        /// 
        /// 获取表集合
        /// 
        /// 是否缓存
        /// 
        List GetTableInfoList(bool isCache = true);
        /// 
        /// 获取视图集合
        /// 
        /// 是否缓存
        /// 
        List GetViewInfoList(bool isCache = true);
        /// 
        /// 检测列是否存在
        /// 
        /// 表名
        /// 列名
        /// 
        bool IsAnyColumn(string tableName, string column);
        /// 
        /// 检测约束
        /// 
        /// 约束名称
        /// 
        bool IsAnyConstraint(string constraintName);
        /// 
        /// 检测是否有任何系统表权限 
        /// 
        /// 
        bool IsAnySystemTablePermissions();
        /// 
        /// 检测表是否存在
        /// 
        /// 表名
        /// 是否缓存
        /// 
        bool IsAnyTable(string tableName, bool isCache = true);
        /// 
        /// 检测列是否自增列
        /// 
        /// 表名
        /// 列名
        /// 
        bool IsIdentity(string tableName, string column);
        /// 
        /// 检测列是否主键
        /// 
        /// 表名
        /// 列名
        /// 
        bool IsPrimaryKey(string tableName, string column);
        /// 
        /// 重置列名
        /// 
        /// 表名
        /// 旧列名
        /// 新列名
        /// 
        bool RenameColumn(string tableName, string oldColumnName, string newColumnName);
        /// 
        /// 重置表数据
        /// 
        /// 表名
        /// 
        bool TruncateTable(string tableName);
        /// 
        /// 修改列信息
        /// 
        /// 表名
        /// 列信息
        /// 
        bool UpdateColumn(string tableName, DbColumnInfo column);

        /// 
        /// 获取数据库时间
        /// 
        /// 返回值
        DateTime GetDataBaseTime();
        #endregion

        #region 新增 
        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象   
        /// 操作影响的行数
        int Add(T entity) where T : class, new();

        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        /// 泛型集合
        /// 操作影响的行数
        int Add(List entitys) where T : class, new();

        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        /// 字典集合(Key:列名 Value:值) 
        /// 操作影响的行数
        int Add(Dictionary keyValues) where T : class, new();

        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象  
        /// 返回实体
        T AddReturnEntity(T entity) where T : class, new();

        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象  
        /// 返回自增列
        int AddReturnIdentity(T entity) where T : class, new();
        /// 
        /// 新增
        ///  
        /// 泛型参数(集合成员的类型)
        ///  实体对象  
        /// 返回bool
        bool AddReturnBool(T entity) where T : class, new();

        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        /// 泛型集合
        /// 返回bool
        bool AddReturnBool(List entitys) where T : class, new();
        #endregion

        #region 修改 

        /// 
        /// 修改(主键是更新条件)
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件  
        /// 不更新的列
        ///  是否加锁  
        /// 操作影响的行数
        int Update(T entity, List lstIgnoreColumns = null, bool isLock = true) where T : class, new(); 

        /// 
        /// 修改(主键是更新条件)
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象集合(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件  
        /// 不更新的列
        ///  是否加锁  
        /// 操作影响的行数
        int Update(List entitys, List lstIgnoreColumns = null, bool isLock = true) where T : class, new();

        /// 
        /// 修改
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象  
        ///  条件   
        /// 不更新的列
        ///  是否加锁  
        /// 操作影响的行数
        int Update(T entity, Expression> where , List lstIgnoreColumns = null,
            bool isLock = true) where T : class, new();

        /// 
        /// 修改
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象  
        ///  条件   
        ///  是否加锁  
        /// 操作影响的行数
        int Update(Expression> update, Expression> where = null, bool isLock = true) where T : class, new();

        /// 
        /// 修改
        /// 
        /// 泛型参数(集合成员的类型)
        /// 字典集合(Key:列名 Value:值) 
        ///  条件   
        ///  是否加锁  
        /// 操作影响的行数
        int Update(Dictionary keyValues, Expression> where = null, bool isLock = true)
            where T : class, new();

        /// 
        /// 批量修改需要更新的列
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件  
        /// 更新指定列
        /// 条件(为空则以主键更新,反之需要把wherecolumns中的列加到UpdateColumns中)
        ///  是否加锁  
        /// 操作影响的行数
        int UpdateColumns(List entitys, Expression> updateColumns,
            Expression> wherecolumns = null, bool isLock = true) where T : class, new();

        /// 
        /// 修改 通过RowVer及主键Code 更新
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象  
        /// 不更新的列
        ///  是否加锁  
        /// 操作影响的行数
        int UpdateRowVer(T entity, List lstIgnoreColumns = null, bool isLock = true)where T : class, new();

        /// 
        /// 修改 通过RowVer及主键Code 更新
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象   
        ///  更新条件   
        ///  是否加锁  
        /// 操作影响的行数
        int UpdateRowVer(Expression> update, Dictionary where, bool isLock = true) where T : class, new();
        #endregion

        #region 删除

        /// 
        /// 删除 通过主键数据
        /// 
        /// 泛型参数(集合成员的类型)
        /// 主键值 
        ///  是否加锁  
        /// 操作影响的行数
        int DeleteByPrimary(List primaryKeyValues, bool isLock = true) where T : class, new();

        /// 
        /// 删除
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件  
        ///  是否加锁  
        /// 操作影响的行数
        int Delete(T entity, bool isLock = true) where T : class, new();

        /// 
        /// 删除
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象 (必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 
        ///  是否加锁  
        /// 操作影响的行数
        int Delete(List entity, bool isLock = true) where T : class, new();

        /// 
        /// 删除
        /// 
        /// 泛型参数(集合成员的类型)
        ///  条件  
        ///  是否加锁  
        /// 操作影响的行数
        int Delete(Expression> where, bool isLock = true) where T : class, new();

        /// 
        /// 通过多值(主键)删除数据集
        /// 
        /// 泛型参数(集合成员的类型) 
        /// 数据集合
        /// 
        int DeleteIn(List inValues) where T : class, new();

        #endregion

        #region 查询

        #region 数据源

        ///// 
        ///// 查询数据源
        ///// 
        ///// 泛型参数(集合成员的类型
        ///// 数据源
        //ISugarQueryable Queryable() where T : class, new();

        #endregion

        #region 多表查询  

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 返回对象
        /// 关联表达式 (t1,t2) => new object[] {JoinType.Left,t1.UserNo==t2.UserNo}
        /// 返回表达式 (t1, t2) => new { Id =t1.UserNo, Id1 = t2.UserNo}
        /// 查询表达式 (t1, t2) =>t1.UserNo == "")   
        /// 
        List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 返回对象
        /// 关联表达式
        /// 返回表达式
        /// 查询表达式  
        /// 
        List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new();


        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 返回对象
        /// 关联表达式
        /// 返回表达式
        /// 查询表达式  
        /// 
        List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 返回对象
        /// 关联表达式
        /// 返回表达式
        /// 查询表达式  
        /// 
        List QueryMuch(
           Expression> joinExpression,
           Expression> selectExpression,
           Expression> whereLambda = null) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 实体9
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 返回对象
        /// 关联表达式 (t1,t2) => new object[] {JoinType.Left,t1.UserNo==t2.UserNo}
        /// 返回表达式 (t1, t2) => new { Id =t1.UserNo, Id1 = t2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();


        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();


        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 实体9
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new();
        #endregion

        #region  查询

        /// 
        /// 查询-返回自定义数据
        /// 
        /// 泛型参数(集合成员的类型)
        /// 返回值类型
        /// 返回值表达式 
        /// 查询表达式 
        /// 
        TResult QuerySelect(Expression> expression,Expression> whereLambda = null) where T : class, new();

        /// 
        /// 查询-返回自定义数据
        /// 
        /// 泛型参数(集合成员的类型)
        /// 返回值类型
        /// 返回值表达式 
        /// 查询表达式 
        /// 
        List QuerySelectList(Expression> expression,Expression> whereLambda = null) where T : class, new();

        /// 
        /// 查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 查询表达式 
        /// 
        T Query(Expression> whereLambda = null) where T : class, new();

        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件 
        /// 实体
        List QueryWhereList(Expression> whereLambda = null) where T : class, new();
        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件 
        /// 实体
        List QueryList(QueryDescriptor query = null) where T : class, new();

        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// sql 
        /// 实体
        List QuerySqlList(string sql) where T : class, new();

        /// 
        /// 分页查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件
        /// 总行数
        /// 实体
        List QueryPageList(QueryDescriptor query, out int totalCount) where T : class, new();

        /// 
        /// 通过多值查询数据集
        /// 
        /// 泛型参数(集合成员的类型)
        /// 字段名
        /// 数据集合
        /// 
        List In(string inFieldName, List inValues) where T : class, new();

        /// 
        /// 通过多值(主键)查询数据集
        /// 
        /// 泛型参数(集合成员的类型)
        /// 主键数据集合
        /// 
        List In(List values) where T : class, new(); 

        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 查询表达式 
        /// 实体
        DataTable QueryDataTable(Expression> whereLambda = null) where T : class, new();

        /// 
        /// 查询集合
        ///  
        /// sql 
        /// 实体
        DataTable QueryDataTable(string sql);

        /// 
        /// 查询单个值
        ///  
        /// sql 
        /// 单个值
        object QuerySqlScalar(string sql);

        /// 
        /// 分页查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件
        /// 总行数
        /// DataTable
        DataTable QueryDataTablePageList(QueryDescriptor query, out int totalCount) where T : class, new();

        #endregion

        #region Mapper

        /// 
        /// Mapper查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 操作(it, cache) =>
        /// { 
        ///     var all = cache.GetListByPrimaryKeys(vmodel => vmodel.Id);  //一次性查询出所要的外键引用数据 
        ///     it.School = all.FirstOrDefault(i => i.Id == it.Id); //一对一 
        ///     it.Schools = all.Where(i => i.Id == it.Id).ToList(); //一对多
        ///     /*用C#处理你想要的结果*/
        ///     it.Name = it.Name == null ? "null" : it.Name;
        ///  }
        /// 
        /// 过滤条件
        /// 
        List QueryMapper(Action mapperAction, QueryDescriptor query = null) where T : class, new();

        /// 
        /// Mapper查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 操作(it, cache) =>
        /// { 
        ///     var all = cache.GetListByPrimaryKeys(vmodel => vmodel.Id);  //一次性查询出所要的外键引用数据 
        ///     it.School = all.FirstOrDefault(i => i.Id == it.Id); //一对一 
        ///     it.Schools = all.Where(i => i.Id == it.Id).ToList(); //一对多
        ///     /*用C#处理你想要的结果*/
        ///     it.Name = it.Name == null ? "null" : it.Name;
        ///  }
        /// 
        /// 过滤条件
        /// 
        List QueryMapper(Action mapperAction, Expression> whereLambda = null) where T : class, new();

        #endregion

        #region 存储过程

        /// 
        /// 查询存储过程
        ///  
        /// 存储过程名称
        /// 参数
        /// DataSet
        DataSet QueryProcedureDataSet(string procedureName, List parameters);
        /// 
        /// 查询存储过程
        ///  
        /// 存储过程名称
        /// 参数
        /// DataTable
        DataTable QueryProcedure(string procedureName, List parameters);

        /// 
        /// 查询存储过程
        ///  
        /// 存储过程名称
        /// 参数
        /// 单个值
        object QueryProcedureScalar(string procedureName, List parameters);

        #endregion

        #region 分组

        /// 
        /// 分组
        /// 
        /// 泛型参数(集合成员的类型) 
        /// 分组表达式 
        /// 查询表达式 
        /// 
        List GroupBy(Expression> groupByLambda,Expression> whereLambda = null) where T : class, new();

        /// 
        /// 分组-返回自定义数据
        /// 
        /// 泛型参数(集合成员的类型)
        /// 返回值类型
        /// 返回值表达式 
        /// 分组表达式 
        /// 查询表达式 
        /// 
        List GroupBy(Expression> expression,
            Expression> groupByLambda, Expression> whereLambda = null)
            where T : class, new();

        #endregion

        #region Json

        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 查询表达式 
        /// Json
        string QueryJson(Expression> whereLambda = null) where T : class, new();

        #endregion

        #region 其它

        /// 
        /// 查询前多少条数据
        /// 
        /// 泛型参数(集合成员的类型
        /// 查询表达式
        /// 数量
        /// 
        List Take(Expression> whereLambda, int num) where T : class, new();

        /// 
        /// 查询单条数据
        /// 
        /// 泛型参数(集合成员的类型
        /// 查询表达式 
        /// 
        T First(Expression> whereLambda) where T : class, new();

        /// 
        /// 是否存在
        /// 
        /// 泛型参数(集合成员的类型
        /// 查询表达式 
        /// 
        bool IsExist(Expression> whereLambda) where T : class, new();

        /// 
        /// 合计
        /// 
        /// 泛型参数(集合成员的类型
        /// 字段 
        /// 
        int Sum(string field) where T : class, new();

        /// 
        /// 最大值
        /// 
        /// 泛型参数(集合成员的类型
        /// 返回类型
        /// 字段 
        /// 
        TResult Max(string field) where T : class, new();

        /// 
        /// 最小值
        /// 
        /// 泛型参数(集合成员的类型
        /// 返回类型
        /// 字段 
        /// 
        TResult Min(string field) where T : class, new();
        /// 
        /// 平均值
        /// 
        /// 泛型参数(集合成员的类型
        /// 字段 
        /// 
        int Avg(string field) where T : class, new();
         
        /// 
        /// 生成流水号
        /// 
        /// 列名
        /// 前缀
        /// 流水号长度
        /// 日期格式(yyyyMMdd) 为空前缀后不加日期,反之加
        /// 
        string CustomNumber(string key, string prefix = "", int fixedLength = 4, string dateFomart = "")where T : class, new();

        /// 
        /// 生成流水号
        /// 
        /// 列名
        /// 数量
        /// 前缀
        /// 流水号长度
        /// 日期格式(yyyyMMdd) 为空前缀后不加日期,反之加
        /// 
        List CustomNumber(string key,int num, string prefix = "", int fixedLength = 4, string dateFomart = "") where T : class, new();

        #endregion


        #endregion
    }
}

 
  
#region << 版 本 注 释 >>
/*---------------------------------------------------------------- 
* 类 名 称 :SugerHandler
* 类 描 述 :    
* 作    者 :xnlzg
* 创建时间 :2018/7/23 15:52:47
* 更新时间 :2018/7/23 15:52:47
* 说    明 :
using ( var db = SugarHandler.Instance())
{
    db.BeginTran(); 
    var userInfo = db.Query(m => m.UserName == userLogin.UserName); 
    db.CommitTran();
}
* 版 本 号 :v1.0.0.0
*******************************************************************
* Copyright @ xnlzg 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq.Expressions;
using OPPO.DBUtility;
using SqlSugar;

namespace XN.Common
{
    /// 
    /// SqlSugar调用类
    /// 
    public class SugerHandler
    {
        #region 初始化
        /// 
        /// 初始化
        /// 
        /// 
        public static ISugerHandler Instance()
        {
            return new SugerRepository();
        }
        /// 
        /// 初始化
        /// 
        /// 服务器IP
        /// 用户名
        /// 密码
        /// 数据库
        /// 
        public static ISugerHandler Instance(string serverIp, string user, string pass, string dataBase)
        {
            var suger = new SugerRepository();
            suger.Instance(serverIp, user, pass, dataBase);
            return suger;
        }

        #endregion
    }
    /// 
    /// SqlSugar操作类型
    /// 
    public class SugerRepository : ISugerHandler
    {

        /// 
        /// 数据库连接对象
        ///  
        public SqlSugarClient DbContext { get; set; } = BaseDbContext.Db;

        /// 
        /// 初始化
        /// 
        /// 服务器IP
        /// 用户名
        /// 密码
        /// 数据库
        /// 
        public void Instance(string serverIp, string user, string pass, string dataBase)
        {
            DbContext = BaseDbContext.GetIntance(serverIp, user, pass, dataBase); 
        }

        #region 事务


        /// 
        /// 事务操作
        /// 注意:代码段里面如果调用本身类其它方法或其它类方法必须带着var db = SugerHandler.Instance()这个db走,不带着走事务回滚会不成功
        ///  
        /// 代码段 
        /// 事务级别
        public void InvokeTransactionScope(Action serviceAction, IsolationLevel level = IsolationLevel.ReadCommitted)
        {
            try
            {
                DbContext.Ado.BeginTran(level);
                serviceAction();
                DbContext.Ado.CommitTran(); 
            }
            catch (Exception ex)
            {
                DbContext.Ado.RollbackTran();
                throw new Exception(ex.Message);
            }
            finally
            {
                Dispose();
            } 
        }
        #endregion
         
        #region 数据库管理
        /// 
        /// 添加列
        /// 
        /// 表名
        /// 列信息
       /// 
        public bool AddColumn(string tableName, DbColumnInfo column)
        {
            return DbContext.DbMaintenance.AddColumn(tableName, column);
        }
        /// 
        /// 添加主键
        /// 
        /// 表名
        /// 列名
       /// 
        public bool AddPrimaryKey(string tableName, string columnName)
        {
            return DbContext.DbMaintenance.AddPrimaryKey(tableName, columnName);
        }
        /// 
        /// 备份数据库
        /// 
        /// 数据库名
        /// 文件名
       /// 
        public bool BackupDataBase(string databaseName, string fullFileName)
        {
            return DbContext.DbMaintenance.BackupDataBase(databaseName, fullFileName);
        }
        /// 
        /// 备份表
        /// 
        /// 旧表名
        /// 行表名
        /// 行数
       /// 
        public bool BackupTable(string oldTableName, string newTableName, int maxBackupDataRows = int.MaxValue)
        {
            return DbContext.DbMaintenance.BackupTable(oldTableName, newTableName, maxBackupDataRows);
        }
        /// 
        /// 创建表
        /// 
        /// 表名
        /// 列集合
        /// 是否创建主键
       /// 
        public bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true)
        {
            return DbContext.DbMaintenance.CreateTable(tableName, columns, isCreatePrimaryKey);
        }
        /// 
        /// 删除列
        /// 
        /// 表名
        /// 列名
       /// 
        public bool DropColumn(string tableName, string columnName)
        {
            return DbContext.DbMaintenance.DropColumn(tableName, columnName);
        }
        /// 
        /// 删除约束
        /// 
        /// 表名
        /// 约束名
       /// 
        public bool DropConstraint(string tableName, string constraintName)
        {
            return DbContext.DbMaintenance.DropConstraint(tableName, constraintName);
        }
        /// 
        /// 删除表
        /// 
        /// 
       /// 
        public bool DropTable(string tableName)
        {
            return DbContext.DbMaintenance.DropTable(tableName);
        }
        /// 
        /// 获取列信息
        /// 
        /// 表名
        /// 是否缓存
       /// 
        public List GetColumnInfosByTableName(string tableName, bool isCache = true)
        {
            return DbContext.DbMaintenance.GetColumnInfosByTableName(tableName, isCache);
        }
        /// 
        /// 获取自增列
        /// 
        /// 表名
       /// 
        public List GetIsIdentities(string tableName)
        {
            return DbContext.DbMaintenance.GetIsIdentities(tableName);
        }
        /// 
        /// 获取主键
        /// 
        /// 表名
       /// 
        public List GetPrimaries(string tableName)
        {
            return DbContext.DbMaintenance.GetPrimaries(tableName);
        }
        /// 
        /// 获取表集合
        /// 
        /// 是否缓存
       /// 
        public List GetTableInfoList(bool isCache = true)
        {
            return DbContext.DbMaintenance.GetTableInfoList(isCache);
        }
        /// 
        /// 获取视图集合
        /// 
        /// 是否缓存
       /// 
        public List GetViewInfoList(bool isCache = true)
        {
            return DbContext.DbMaintenance.GetViewInfoList(isCache);
        }
        /// 
        /// 检测列是否存在
        /// 
        /// 表名
        /// 列名
       /// 
        public bool IsAnyColumn(string tableName, string column)
        {
            return DbContext.DbMaintenance.IsAnyColumn(tableName, column);
        }
        /// 
        /// 检测约束
        /// 
        /// 约束名称
       /// 
        public bool IsAnyConstraint(string constraintName)
        {
            return DbContext.DbMaintenance.IsAnyConstraint(constraintName);
        }
        /// 
        /// 检测是否有任何系统表权限 
        /// 
       /// 
        public bool IsAnySystemTablePermissions()
        {
            return DbContext.DbMaintenance.IsAnySystemTablePermissions();
        }
        /// 
        /// 检测表是否存在
        /// 
        /// 表名
        /// 是否缓存
       /// 
        public bool IsAnyTable(string tableName, bool isCache = true)
        {
            return DbContext.DbMaintenance.IsAnyTable(tableName, isCache);
        }
        /// 
        /// 检测列是否自增列
        /// 
        /// 表名
        /// 列名
       /// 
        public bool IsIdentity(string tableName, string column)
        {
            return DbContext.DbMaintenance.IsIdentity(tableName, column);
        }
        /// 
        /// 检测列是否主键
        /// 
        /// 表名
        /// 列名
       /// 
        public bool IsPrimaryKey(string tableName, string column)
        {
            return DbContext.DbMaintenance.IsPrimaryKey(tableName, column);
        }
        /// 
        /// 重置列名
        /// 
        /// 表名
        /// 旧列名
        /// 新列名
       /// 
        public bool RenameColumn(string tableName, string oldColumnName, string newColumnName)
        {
            return DbContext.DbMaintenance.RenameColumn(tableName, oldColumnName, newColumnName);
        }
        /// 
        /// 重置表数据
        /// 
        /// 表名
       /// 
        public bool TruncateTable(string tableName)
        {
            return DbContext.DbMaintenance.TruncateTable(tableName);
        }
        /// 
        /// 修改列信息
        /// 
        /// 表名
        /// 列信息
       /// 
        public bool UpdateColumn(string tableName, DbColumnInfo column)
        {
            return DbContext.DbMaintenance.UpdateColumn(tableName, column);
        }

        /// 
        /// 获取数据库时间
        /// 
        /// 返回值
        public DateTime GetDataBaseTime()
        {
            return DbContext.GetDate();
        }

        #endregion

        #region 新增 
        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象   
        /// 操作影响的行数
        public int Add(T entity) where T : class, new()
        {
            try
            {
                var result = DbContext.Insertable(entity).ExecuteCommand();
                return result;
            }
            catch (Exception ex)
            {
                
                throw new Exception(ex.Message);
            }
        }

        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        /// 泛型集合 
        /// 操作影响的行数
        public int Add(List entitys) where T : class, new()
        {
            try
            {
                var result = DbContext.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 = DbContext.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 = DbContext.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 = DbContext.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 = DbContext.Insertable(entity).ExecuteCommand()>0;
                return result;
            }
            catch (Exception ex)
            {
                
                throw new Exception(ex.Message);
            }

        }

        /// 
        /// 新增
        /// 
        /// 泛型参数(集合成员的类型)
        /// 泛型集合 
        /// 返回bool
        public bool AddReturnBool(List entitys) where T : class, new()
        {
            try
            {
                var result = DbContext.Insertable(entitys).ExecuteCommand() > 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 = DbContext.Updateable(entity);
                if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
                {
                    up = up.IgnoreColumns(lstIgnoreColumns.Contains);
                } 
                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
            {
                IUpdateable up = DbContext.Updateable(entitys);
                if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
                {
                    up = up.IgnoreColumns(lstIgnoreColumns.Contains);
                }
                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 = DbContext.Updateable(entity);
                if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
                {
                    up = up.IgnoreColumns(lstIgnoreColumns.Contains);
                } 
                    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 = DbContext.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);
            }

        }


        /// 
        /// 修改
        /// 
        /// 泛型参数(集合成员的类型)
        /// 字典集合(Key:列名 Value:值) 
        ///  条件   
        ///  是否加锁  
        /// 操作影响的行数
        public int Update(Dictionary keyValues, Expression> where = null, bool isLock = true) where T : class, new()
        {
            try
            {
                IUpdateable up = DbContext.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
            {
                IUpdateable up = DbContext.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 = DbContext.Updateable(entity);
                if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
                {
                    up = up.IgnoreColumns(lstIgnoreColumns.Contains);
                }
                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);
            }

        }



        /// 
        /// 修改 
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象   
        ///  更新条件   
        ///  是否加锁  
        /// 操作影响的行数
        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 = DbContext.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 int DeleteByPrimary(List primaryKeyValues, bool isLock = true) where T : class, new()
        {
            try
            {
                var result = isLock ?
                    DbContext.Deleteable().In(primaryKeyValues).With(SqlWith.RowLock).ExecuteCommand()
                    : DbContext.Deleteable().In(primaryKeyValues).ExecuteCommand();
                return result;
            }
            catch (Exception ex)
            {
                
                throw new Exception(ex.Message);
            }

        }
        /// 
        /// 删除
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象 (必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 
        ///  是否加锁  
        /// 操作影响的行数
        public int Delete(T entity, bool isLock = true) where T : class, new()
        {
            try
            {
                var result = isLock ?
                    DbContext.Deleteable(entity).With(SqlWith.RowLock).ExecuteCommand()
                    : DbContext.Deleteable(entity).ExecuteCommand();
                return result;
            }
            catch (Exception ex)
            {
                
                throw new Exception(ex.Message);
            }

        }
        /// 
        /// 删除
        /// 
        /// 泛型参数(集合成员的类型)
        ///  实体对象 (必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件 
        ///  是否加锁  
        /// 操作影响的行数
        public int Delete(List entity, bool isLock = true) where T : class, new()
        {
            try
            {
                var result = isLock ?
                    DbContext.Deleteable(entity).With(SqlWith.RowLock).ExecuteCommand()
                    : DbContext.Deleteable(entity).ExecuteCommand();
                return result;
            }
            catch (Exception ex)
            {
                
                throw new Exception(ex.Message);
            }

        }
        /// 
        /// 删除
        /// 
        /// 泛型参数(集合成员的类型)
        ///  条件  
        ///  是否加锁  
        /// 操作影响的行数
        public int Delete(Expression> where, bool isLock = true) where T : class, new()
        {
            try
            {
                var result = isLock ?
                    DbContext.Deleteable().Where(where).With(SqlWith.RowLock).ExecuteCommand()
                    : DbContext.Deleteable().Where(where).ExecuteCommand();
                return result;
            }
            catch (Exception ex)
            {
                
                throw new Exception(ex.Message);
            }

        }
        
        /// 
        /// 通过多值(主键)删除数据集
        /// 
        /// 泛型参数(集合成员的类型) 
        /// 数据集合
       /// 
        public int DeleteIn(List inValues) where T : class, new()
        {
            return DbContext.Deleteable().With(SqlWith.RowLock).In(inValues).ExecuteCommand();
        }
         
        #endregion

        #region 查询

        #region 数据源

        ///// 
        ///// 查询数据源
        ///// 
        ///// 泛型参数(集合成员的类型
        ///// 数据源
        //public ISugarQueryable Queryable() where T : class, new()
        //{
        //    return DbContext.Queryable();
        //}

        #endregion

        #region 多表查询  

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 返回对象
        /// 关联表达式 (t1,t2) => new object[] {JoinType.Left,t1.UserNo==t2.UserNo}
        /// 返回表达式 (t1, t2) => new { Id =t1.UserNo, Id1 = t2.UserNo}
        /// 查询表达式 (t1, t2) =>t1.UserNo == "")  
        /// 
        public List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体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 List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        }


        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
       /// 
        public List QueryMuch(
                       Expression> joinExpression,
                       Expression> selectExpression,
                       Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
       /// 
        public List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        public List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        }
        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        public List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        public List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 实体9
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询表达式 (w1, w2) =>w1.UserNo == "")  
        /// 
        public List QueryMuch(
            Expression> joinExpression,
            Expression> selectExpression,
            Expression> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return DbContext.Queryable(joinExpression).Select(selectExpression).ToList();
            }
            return DbContext.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToList();
        } 

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 返回对象
        /// 关联表达式 (t1,t2) => new object[] {JoinType.Left,t1.UserNo==t2.UserNo}
        /// 返回表达式 (t1, t2) => new { Id =t1.UserNo, Id1 = t2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }


        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }


        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
                       Expression> joinExpression,
                       Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }
        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }

        /// 
        ///查询-多表查询 
        /// 
        /// 实体1
        /// 实体2
        /// 实体3
        /// 实体4
        /// 实体5
        /// 实体6
        /// 实体7
        /// 实体8
        /// 实体9
        /// 返回对象
        /// 关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}
        /// 返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}
        /// 查询条件  
        /// 总行数  
        /// 
        public List QueryMuchDescriptor(
            Expression> joinExpression,
            Expression> selectExpression,
            QueryDescriptor query, out int totalCount) where T : class, new()
        {
            var up = DbContext.Queryable(joinExpression).Select(selectExpression).MergeTable();

            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);
            }

            totalCount = 0;
            if (query.PageSize == 0)
            {
                var datas = up.ToList();
                totalCount = datas.Count;
                return datas;
            }
            else
            {
                var datas = up.ToPageList(query.PageIndex, query.PageSize, ref totalCount);
                return datas;
            }
        }

        #endregion

        #region 查询
        /// 
        /// 查询-返回自定义数据
        /// 
        /// 泛型参数(集合成员的类型)
        /// 返回值类型
        /// 返回值表达式 
        /// 查询表达式 
        /// 
        public TResult QuerySelect( Expression> expression,Expression> whereLambda = null) where T : class, new()
        { 
            var datas = DbContext.Queryable().With(SqlWith.NoLock).Where(whereLambda).Select(expression).First();
            return datas;
        }
        /// 
        /// 查询-返回自定义数据
        /// 
        /// 泛型参数(集合成员的类型)
        /// 返回值类型
        /// 返回值表达式 
        /// 查询表达式 
        /// 
        public List QuerySelectList(Expression> expression, Expression> whereLambda = null) where T : class, new()
        {
            var datas = DbContext.Queryable().With(SqlWith.NoLock).Where(whereLambda).Select(expression).ToList();
            return datas;
        }
        /// 
        /// 查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 查询表达式 
        /// 
        public T Query(Expression> whereLambda = null) where T : class, new()
        {
            ISugarQueryable up = DbContext.Queryable().With(SqlWith.NoLock); 
            if (whereLambda != null)
            {
                up = up.Where(whereLambda);
            } 
            return up.First();
        }
        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件 
        /// 实体
        public List QueryWhereList(Expression> whereLambda = null) where T : class, new()
        {
            ISugarQueryable up = DbContext.Queryable().With(SqlWith.NoLock);
            if (whereLambda != null)
            {
                up = up.Where(whereLambda);
            }
            return up.ToList();
        }

        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件 
        /// 实体
        public List QueryList(QueryDescriptor query=null) where T : class, new()
        {
            ISugarQueryable up = DbContext.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();
        }
        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// sql  
        /// 实体
        public List QuerySqlList(string sql) where T : class, new()
        {
            return DbContext.SqlQueryable(sql).ToList();
        }
         
        /// 
        /// 分页查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件
        /// 总行数
        /// 实体
        public List QueryPageList(QueryDescriptor query, out int totalCount) where T : class, new()
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }
            var listDatas = DbContext.Queryable();
            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()
        {
            return DbContext.Queryable().In(inFieldName, inValues).ToList(); 
        }
        /// 
        /// 查询集合-通过多值(主键)
        /// 
        /// 泛型参数(集合成员的类型)
        /// 主键数据集合
       /// 
        public List In(List values) where T : class, new()
        {
            return DbContext.Queryable().In(values).ToList();
        } 

        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 查询表达式  
        /// 实体
        public DataTable QueryDataTable(Expression> whereLambda = null) where T : class, new()
        {
            ISugarQueryable up = DbContext.Queryable().With(SqlWith.NoLock);
            if (whereLambda != null)
            {
                up = up.Where(whereLambda);
            } 
            return up.ToDataTable();
        }
         
        /// 
        /// 查询集合
        ///  
        /// sql 
        /// 实体
        public DataTable QueryDataTable(string sql)
        {
            return DbContext.Ado.GetDataTable(sql);
        }

        /// 
        /// 查询单个值
        ///  
        /// sql 
        /// 单个值
        public object QuerySqlScalar(string sql)
        {
            return DbContext.Ado.GetScalar(sql);
        }
        /// 
        /// 分页查询
        /// 
        /// 泛型参数(集合成员的类型)
        /// 过滤条件
        /// 总行数
        /// DataTable
        public DataTable QueryDataTablePageList(QueryDescriptor query, out int totalCount) where T : class, new()
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }
            var listDatas = DbContext.Queryable();
            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 Mapper

        /// 
        /// Mapper查询 一对多和一对一
        /// 
        /// 泛型参数(集合成员的类型)
        /// 操作(it, cache) =>
        /// { 
        ///     var all = cache.GetListByPrimaryKeys(vmodel => vmodel.Id);  //一次性查询出所要的外键引用数据 
        ///     it.School = all.FirstOrDefault(i => i.Id == it.Id); //一对一 
        ///     it.Schools = all.Where(i => i.Id == it.Id).ToList(); //一对多
        ///     /*用C#处理你想要的结果*/
        ///     it.Name = it.Name == null ? "null" : it.Name;
        ///  }
        /// 
        /// 过滤条件
        /// 
        public List QueryMapper(Action mapperAction,QueryDescriptor query = null) where T : class, new()
        {
            ISugarQueryable up = DbContext.Queryable(); 
            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);
                }
            }
            var datas = up.Mapper(mapperAction).ToList();
            return datas;
        }

        /// 
        /// Mapper查询 一对多和一对一
        /// 
        /// 泛型参数(集合成员的类型)
        /// 操作(it, cache) =>
        /// { 
        ///     var all = cache.GetListByPrimaryKeys(vmodel => vmodel.Id);  //一次性查询出所要的外键引用数据 
        ///     it.School = all.FirstOrDefault(i => i.Id == it.Id); //一对一 
        ///     it.Schools = all.Where(i => i.Id == it.Id).ToList(); //一对多
        ///     /*用C#处理你想要的结果*/
        ///     it.Name = it.Name == null ? "null" : it.Name;
        ///  }
        /// 
        /// 过滤条件
        /// 
        public List QueryMapper(Action mapperAction, Expression> whereLambda = null) where T : class, new()
        {
            ISugarQueryable up = DbContext.Queryable();
            if (whereLambda != null)
            {
                up = up.Where(whereLambda);
            }
            var datas = up.Mapper(mapperAction).ToList();
            return datas;
        }

        #endregion

        #region 分组
        /// 
        /// 分组
        /// 
        /// 泛型参数(集合成员的类型) 
        /// 分组表达式 
        /// 查询表达式 
        /// 
        public List GroupBy(Expression> groupByLambda, Expression> whereLambda = null) where T : class, new()
        {
            var datas = DbContext.Queryable().With(SqlWith.NoLock).Where(whereLambda).GroupBy(groupByLambda).ToList();
            return datas;
        }

        /// 
        /// 分组-返回自定义数据
        /// 
        /// 泛型参数(集合成员的类型)
        /// 返回值类型
        /// 返回值表达式 
        /// 分组表达式 
        /// 查询表达式 
        /// 
        public List GroupBy(Expression> expression, Expression> groupByLambda, Expression> whereLambda = null) where T : class, new()
        {
            var datas = DbContext.Queryable().With(SqlWith.NoLock).Where(whereLambda).GroupBy(groupByLambda).Select(expression).ToList();
            return datas;
        } 

        #endregion

        #region 存储过程

        /// 
        /// 查询存储过程
        ///  
        /// 存储过程名称
        /// 参数
        /// DataSet
        public DataSet QueryProcedureDataSet(string procedureName, List parameters)
        {
            var listParams = new List();
            foreach (var p in parameters)
            {
                listParams.Add(new SugarParameter(p.ParameterName, p.Value, null, p.Direction));
            }
            var datas = DbContext.Ado.UseStoredProcedure().GetDataSetAll(procedureName, listParams);
            return datas;
        }
        /// 
        /// 查询存储过程
        ///  
        /// 存储过程名称
        /// 参数
        /// DataTable
        public DataTable QueryProcedure(string procedureName, List parameters)
        {
            var listParams = new List();
            foreach (var p in parameters)
            { 
                listParams.Add(new SugarParameter(p.ParameterName,p.Value,null,p.Direction));
            }
            var datas = DbContext.Ado.UseStoredProcedure().GetDataTable(procedureName, listParams);
            return datas;
        }

        /// 
        /// 查询存储过程
        ///  
        /// 存储过程名称
        /// 参数
        /// 单个值
        public object QueryProcedureScalar(string procedureName, List parameters)
        {
            var listParams = new List();
            foreach (var p in parameters)
            {
                listParams.Add(new SugarParameter(p.ParameterName, p.Value, null, p.Direction));
            }
            var datas = DbContext.Ado.UseStoredProcedure().GetScalar(procedureName, listParams);
            return datas;
        }

        #endregion

        #region Json

        /// 
        /// 查询集合
        /// 
        /// 泛型参数(集合成员的类型)
        /// 查询表达式  
        /// Json
        public string QueryJson(Expression> whereLambda = null) where T : class, new()
        {
            ISugarQueryable up = DbContext.Queryable().With(SqlWith.NoLock);
            if (whereLambda != null)
            {
                up = up.Where(whereLambda);
            } 
            return up.ToJson();
        }

        #endregion

        #region 其它

        /// 
        /// 查询前多少条数据
        /// 
        /// 泛型参数(集合成员的类型
        /// 查询表达式
        /// 数量
       /// 
        public List Take(Expression> whereLambda, int num) where T : class, new()
        {
            var datas = DbContext.Queryable().With(SqlWith.NoLock).Where(whereLambda).Take(num).ToList();
            return datas;
        }

        /// 
        /// 查询单条数据
        /// 
        /// 泛型参数(集合成员的类型
        /// 查询表达式 
       /// 
        public T First(Expression> whereLambda) where T : class, new()
        {
            var datas = DbContext.Queryable().With(SqlWith.NoLock).Where(whereLambda).First();
            return datas;
        }
        /// 
        /// 是否存在
        /// 
        /// 泛型参数(集合成员的类型
        /// 查询表达式 
       /// 
        public bool IsExist(Expression> whereLambda) where T : class, new()
        {
            var datas = DbContext.Queryable().Any(whereLambda);
            return datas;
        }
         
        /// 
        /// 合计
        /// 
        /// 泛型参数(集合成员的类型
        /// 字段 
        /// 
        public int Sum(string field) where T : class, new()
        {
            var datas = DbContext.Queryable().Sum(field);
            return datas;
        }
        /// 
        /// 最大值
        /// 
        /// 泛型参数(集合成员的类型
        /// 返回类型
        /// 字段 
        /// 
        public TResult Max(string field) where T : class, new()
        {
            var datas = DbContext.Queryable().Max(field);
            return datas;
        }
        /// 
        /// 最小值
        /// 
        /// 泛型参数(集合成员的类型
        /// 返回类型
        /// 字段 
        /// 
        public TResult Min(string field) where T : class, new()
        {
            var datas = DbContext.Queryable().Min(field);
            return datas;
        }

        /// 
        /// 平均值
        /// 
        /// 泛型参数(集合成员的类型
        /// 字段 
       /// 
        public int Avg(string field) where T : class, new()
        {
            var datas = DbContext.Queryable().Avg(field);
            return datas;
        }

        /// 
        /// 生成流水号
        /// 
        /// 列名
        /// 前缀
        /// 流水号长度
        /// 日期格式(yyyyMMdd) 为空前缀后不加日期,反之加
        /// 
        public string CustomNumber(string key, string prefix = "", int fixedLength = 4, string dateFomart = "") where T : class, new()
        {

            var listNumber = CustomNumber(key, 1,prefix, fixedLength, dateFomart);
            return listNumber[0];
        }
        /// 
        /// 生成流水号
        /// 
        /// 列名
        /// 前缀
        /// 流水号长度
        /// 日期格式(yyyyMMdd) 为空前缀后不加日期,反之加
        /// 数量
        /// 
        public List CustomNumber(string key,int num, string prefix = "", int fixedLength = 4,string dateFomart = "") where T : class, new()
        {

            List numbers = new List();
            var dateValue = dateFomart == "" ? "" : DateTime.Now.ToString(dateFomart);
            var fix = prefix.ToUpper() + dateValue;
            var maxValue = DbContext.Queryable().Where(key + " LIKE '" + fix + "%' AND LEN(" + key + ")=" + (fix.Length + fixedLength)).Select(key).Max(key);

            if (maxValue == null)
            {
                for (var i = 0; i < num; i++)
                {
                    var tempNumber = fix + (i + 1).ToString().PadLeft(fixedLength, '0');
                    numbers.Add(tempNumber);
                } 
            }
            else
            { 
                if (maxValue.Substring(0, maxValue.Length - fixedLength) == prefix + dateValue)
                {
                    var tempLast = maxValue.Substring(maxValue.Length - fixedLength);
                    for (var i = 0; i < num; i++)
                    {
                        var tempNumber = fix + (int.Parse(tempLast) + i + 1).ToString().PadLeft(fixedLength, '0');
                        numbers.Add(tempNumber);
                    } 
                }
                else
                {
                    for (var i = 0; i < num; i++)
                    {
                        var tempNumber = fix + (i + 1).ToString().PadLeft(fixedLength, '0');
                        numbers.Add(tempNumber);
                    }
                }
            } 
            return numbers;
        }
        #endregion
         
        #endregion

        #region 私有方法
        /// 
        /// 过滤条件转换
        /// 
        /// 过滤条件
       /// 
        private List ParseCondition(List contitons)
        {
            var conds = new List();
            contitons.Insert(0, new QueryCondition
            {
                Operator = QueryOperator.Equal,
                Key = "1",
                Value = "1"
            });
            foreach (var con in contitons)
            {
                if (con.Key.Contains(","))
                {
                    conds.Add(ParseKeyOr(con));
                }
                else if (con.Operator == QueryOperator.DateRange)
                {
                    conds.AddRange(ParseRange(con,con.Operator));
                }
                else
                {
                    conds.Add(new ConditionalModel()
                    {
                        FieldName = con.Key,
                        ConditionalType = (ConditionalType)(int)con.Operator,
                        FieldValue = con.Value.ToString()
                    });
                } 
            }

            return conds;
        }
        /// 
        /// 转换Or条件
        /// 
        /// 过滤条件
       /// 
        private ConditionalCollections ParseKeyOr(QueryCondition condition)
        {
            var objectKeys = condition.Key.Split(',');
            var conditionalList = new List>();
            var num = 0;
            foreach (var objKey in objectKeys)
            { 
                if (num == 0)
                {
                    var cond = new KeyValuePair
                    (WhereType.And, new ConditionalModel()
                    {
                        FieldName = objKey,
                        ConditionalType = (ConditionalType)(int)condition.Operator,
                        FieldValue = condition.Value.ToString()
                    });
                    conditionalList.Add(cond);
                }
                else
                {
                    var cond = new KeyValuePair
                    (WhereType.Or, new ConditionalModel()
                    {
                        FieldName = objKey,
                        ConditionalType = (ConditionalType)(int)condition.Operator,
                        FieldValue = condition.Value.ToString()
                    });
                    conditionalList.Add(cond);
                }
                
                num++;
            }
            return new ConditionalCollections { ConditionalList = conditionalList };
        }

        /// 
        /// 转换区域
        /// 
        /// 过滤条件
        /// 条件类型
        /// 
        private List ParseRange(QueryCondition condition, QueryOperator queryOperator)
        {
            var objectValue = condition.Value.ToString().Split('|');
            
            var conditionalList = new List();
            if (objectValue.Length == 2)
            {
                var startValue = objectValue[0];
                var endValue = objectValue[1];
                if (queryOperator == QueryOperator.DateRange)
                {
                    if (startValue.IndexOf(":", StringComparison.Ordinal) == -1)
                    {
                        startValue = startValue + " 00:00:00";
                    }
                    if (endValue.IndexOf(":", StringComparison.Ordinal) == -1)
                    {
                        endValue = endValue + " 23:59:59";
                    }
                }
                if (!string.IsNullOrWhiteSpace(objectValue[0]))
                {
                    conditionalList.Add(new ConditionalModel()
                    {
                        FieldName = condition.Key,
                        ConditionalType = ConditionalType.GreaterThanOrEqual,
                        FieldValue = startValue
                    });
                }
                if (!string.IsNullOrWhiteSpace(objectValue[1]))
                {
                    conditionalList.Add(new ConditionalModel()
                    {
                        FieldName = condition.Key,
                        ConditionalType = ConditionalType.LessThanOrEqual,
                        FieldValue = endValue
                    });
                }
            } 
            return conditionalList;
        }


        /// 
        /// 排序转换
        /// 
        /// 排序
        /// 
        private string ParseOrderBy(List orderBys)
        {
            var conds = "";
            foreach (var con in orderBys)
            {
                switch (con.Order)
                {
                    case OrderSequence.Asc:
                        conds += $"{con.Sort} asc,";
                        break;
                    case OrderSequence.Desc:
                        conds += $"{con.Sort} desc,";
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            return conds.TrimEnd(',');
        }
        #endregion

        /// 
        /// 
        /// 释放
        /// 
        public void Dispose()
        {
            
            DbContext.Ado.Dispose(); 
            DbContext.Dispose();

        }
    }
}

 
  

5wbk
SqlSugar 封装.Net Core和.Net 二个版本_第1张图片

你可能感兴趣的:(SqlSugar框架学习)