using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Collections; using DapperORMCore.Dapper.BaseModel; using DapperORMCore.Model.CoreModel; using DapperORMCore.String.Enums; using DapperORMCore.Model.BaseModel; using DapperORMCore.String.Consts; namespace DapperORMCore.Dapper { #region 扩展Dapper操作 /// /// 获取对应操作语句 /// public static class DapperSQLExtensions { #region add /// /// 插入 返回字段限定 /// /// /// /// /// /// /// /// public static string InsertOutParm(this IDbConnection con, T item, IEnumerable filterNames, string outFieldName, IDbTransaction transaction = null) where T : class { var outSql = DynamicQuery.GetInsertQuery(typeof(T).Name, item, outFieldName, filterNames); return outSql; } /// /// 插入数据模型 /// /// /// /// /// /// /// public static string Insert(this IDbConnection con, T item, string[] nofilters, IDbTransaction transaction = null) where T : class { var outSql = DynamicQuery.GetInsertQuery(typeof(T).Name, item, "", nofilters); return outSql; } /// /// 插入数据模型(不支持DataTable) /// /// /// /// /// /// /// public static string Insert(this IDbConnection con, object item, string tableName, string[] nofilters, IDbTransaction transaction = null) { var outSql = DynamicQuery.GetInsertQuery(tableName, item, "", nofilters); return outSql; } #endregion #region delete /// /// 删除数据模型 /// /// /// /// /// /// public static string Delete(this IDbConnection con, T item, string identityFieldName, IDbTransaction transaction = null) where T : class { //TODO以后这里还要优化,这里只支持一个字段主键 var props = typeof(T).GetProperties(); var columns = props.Select(p => p.Name).Where(s => s == identityFieldName).ToArray(); var columnsValue = props.Where(s => s.Name == identityFieldName). Select(p => p.GetValue(item, null).ToString()).FirstOrDefault(); var parameters = columns.Select(name => "and " + name + SQLBaseString._TO + "'" + columnsValue + "'").ToList(); var outSql = string.Join(SQLBaseString._AND, parameters); outSql = string.Format(SQLString._DeleteBase, typeof(T).Name, outSql); //var result = con.Query(sql, item, transaction); return outSql; } /// /// 删除单一条件SQL记录 /// /// /// /// /// /// public static string Delete(this IDbConnection con, string fieldName, string value, IDbTransaction transaction = null) where T : class { var whereParm = string.Format(SQLBaseString._FIELD_VALUE, fieldName, value); var outSql = DynamicQuery.GetDeleteQuery(typeof(T).Name, whereParm); //con.Query(sql, transaction); return outSql; } /// /// 删除多个条件SQL记录 /// /// /// /// /// /// public static string Delete(this IDbConnection con, IEnumerable fieldKeyList, IDbTransaction transaction = null) where T : class { var whereParm = DynamicQuery.GetWhereSQL(fieldKeyList); var outSql = DynamicQuery.GetDeleteQuery(typeof(T).Name, whereParm); return outSql; } /// /// 删除多个条件SQL记录 /// /// /// /// /// /// public static string Delete(this IDbConnection con, string tableName, string fieldName, string value, IDbTransaction transaction = null) where T : class { var outSql = string.Format(SQLString._DeleteBase, tableName, string.Format("and {0}='1'", fieldName, value)); return outSql; } /// /// 删除表 /// /// /// /// /// /// public static string DropTable(this IDbConnection con, T item, IDbTransaction transaction = null) where T : class { var outSql = DynamicQuery.GetDropTableQuery(typeof(T).GetType().Name); return outSql; } #endregion #region update /// /// 更新模型数据 /// /// /// /// /// public static string Update(this IDbConnection con, T item, string identityFieldName, string noUpdateIdentityFieldName, IDbTransaction transaction = null) where T : class { var outSql = DynamicQuery.GetUpdateQuery(typeof(T).Name, item, identityFieldName, noUpdateIdentityFieldName); return outSql; } /// /// 更新模型数据Value /// /// /// /// /// /// /// /// /// public static string Update(this IDbConnection con, T item, string value, string identityFieldName, string noUpdateIdentityFieldName, IDbTransaction transaction = null) where T : class { var outSql = DynamicQuery.GetUpdateQuery(typeof(T).Name, item, value, identityFieldName, noUpdateIdentityFieldName); return outSql; } /// /// 更新模型数据Object /// /// /// /// /// /// /// /// /// public static string Update(this IDbConnection con, object item, string value, string identityFieldName, string noUpdateIdentityFieldName, IDbTransaction transaction = null) { var outSql = DynamicQuery.GetUpdateQuery(item.GetType().Name, item, value, identityFieldName, noUpdateIdentityFieldName); return outSql; } /// /// 更新拼接语句 /// /// /// /// /// /// /// /// public static string Update(this IDbConnection con, IEnumerable whereKeyList, IEnumerable setKeyList, IDbTransaction transaction = null) where T : class { var tableName = typeof(T).Name; var whereInfo = string.Join(SQLBaseString._AND, whereKeyList.Select(m => m.FieldName + "='" + m.Value + "'")); var setInfo = string.Join(",", setKeyList.Select(m => m.FieldName + "='" + m.Value + "'")); var outSql = string.Format(SQLString._UpdateBase, tableName, setInfo, whereInfo); con.Execute(outSql, null, transaction); return outSql; } /// /// 更新模型数据SQL /// /// /// /// /// /// public static string Update(this IDbConnection con, string sql, IDbTransaction transaction = null) { return sql; } #endregion #region exceute sql /// /// 执行SQL /// /// /// /// /// /// public static string ExceuteSQL(this IDbConnection con, string sql, IDbTransaction transaction = null) { return sql; } #endregion #region sql bulk copy /// /// SQLBulkCopy批量插入数据 /// /// /// /// /// public static DataQueueStatementInfo InsertBatchCopy(this IDbConnection con, IEnumerable list, string tableName ) where T : class { //var outSql = tableName; //if (list.Any()) //{ // Type type = typeof(T); // var result = list.ToList().GetConvertDataTableMapper(); // if (result.Status == OperateStatus.success.ToString()) // { // using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con as SqlConnection)) // { // con.Open(); // bulkCopy.DestinationTableName = tableName; // bulkCopy.BatchSize = list.Count(); // if (result != null && result.Data.Rows.Count != 0) // { // bulkCopy.WriteToServer(result.Data); // } // bulkCopy.Close(); // } // } // return new DataQueueStatementInfo // { // ModelsT = null, // DBOperationType = EnumDBOperationType.BulkCopy, // SQL = sql // }; //} //TODO 批量处理有问题 return null; } /// /// SQLBulkCopy批量插入数据DataTable /// /// /// /// /// public static DataQueueStatementInfo InsertBatchCopyDataTable(this IDbConnection con, DataTable item, string tableName) { //var outSql = tableName; //if (item.Rows.Count>0) //{ // using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con as SqlConnection)) // { // con.Open(); // bulkCopy.DestinationTableName = tableName; // bulkCopy.BatchSize = item.Rows.Count; // bulkCopy.WriteToServer(item); // bulkCopy.Close(); // } // return new DataQueueStatementInfo // { // ModelsT = null, // DBOperationType = EnumDBOperationType.BulkCopy, // SQL = sql // }; //} //TODO 批量处理有问题 return null; } #endregion #region query /// /// 查询语句模型数据 /// /// /// /// /// public static string SelectSQL(this IDbConnection con, string sql) { return sql; } /// /// 查询语句模型表数据 /// /// /// /// /// public static string SelectTable(this IDbConnection con, string sql) { var table = new DataTable("TableTemp"); var reader = con.ExecuteReader(sql); table.Load(reader); return sql; } /// /// 查询语句模型表数据 /// /// /// /// /// /// /// public static string SelectTable(this IDbConnection con, string tableName, string where) { var outSql = string.Format(SQLString._SelectSQLA, tableName, where); var table = new DataTable("TableTemp"); var reader = con.ExecuteReader(outSql); table.Load(reader); return outSql; } /// /// 查询语句模型表数据 /// /// /// /// /// /// /// public static string SelectTable(this IDbConnection con, string tableName, string where, string orderNames, bool isOrderDesc = false) { var outSql = string.Empty; if (isOrderDesc) { outSql = string.Format(SQLString._SelectSqlOrderByDesc, tableName, where == null ? "" : where, orderNames == null ? "" : orderNames); } else { outSql = string.Format(SQLString._SelectSqlOrderByDesc, tableName, where == null ? "" : where, orderNames == null ? "" : orderNames); } var table = new DataTable("TableTemp"); var reader = con.ExecuteReader(outSql); table.Load(reader); return outSql; } /// /// 查询模型数据排序(带限定T) /// /// /// /// 带限定T /// /// public static string SelectT(this IDbConnection con, IEnumerable> fieldKeyList, string sql = "") where T : class { fieldKeyList.ToList().ForEach(m => { m.Value = m.FieldName + m.Operation + "'" + m.Value + "'"; }); var inSql = string.Empty; var fieldString = string.Join(SQLBaseString._AND, fieldKeyList.ToList().Select(m => m.Value).ToArray()); if (string.IsNullOrWhiteSpace(sql)) { inSql = string.Format(SQLString._SelectSQL, typeof(T).Name, fieldString); } else { inSql = string.Format(SQLString._SelectSQL, string.Format(SQLBaseString._INCLUDE_TEMP_VIEW, sql), fieldString); } return inSql; } /// /// 查询模型数据排序(不带限定T) /// /// /// /// 不带限定T /// /// public static string Select(this IDbConnection con, IEnumerable fieldKeyList, string sql = "") where T : class { var inSql = string.Empty; var fieldString = DynamicQuery.GetWhereSQL(fieldKeyList); if (fieldKeyList.Count() != 0) { if (string.IsNullOrWhiteSpace(sql)) { inSql = string.Format(SQLString._SelectSQL, typeof(T).Name, fieldString); } else { inSql = string.Format(SQLString._SelectSQL, string.Format(SQLBaseString._INCLUDE_TEMP_VIEW, sql), fieldString); } } else { if (string.IsNullOrWhiteSpace(sql)) { inSql = string.Format(SQLString._Select, typeof(T).Name); } else { inSql = string.Format(SQLString._SelectSQLA, string.Format(SQLBaseString._INCLUDE_TEMP_VIEW, sql), fieldString); } } return inSql; } /// /// 查询模型数据 /// /// /// /// /// public static string Select(this IDbConnection con, object criteria = null) { var properties = PropertyManage.ParseProperties(criteria); var outSqlPairs = PropertyManage.GetSqlPairs(properties.AllNames, SQLBaseString._AND); var outSql = string.Format(SQLString._SelectSQLA, typeof(T).Name, outSqlPairs); return outSql; } /// /// 查询模型数据排序 /// /// /// /// /// /// public static string SelectOrder(this IDbConnection con, string orderName, bool sleepOrder = false) { var outSql = string.Format(SQLString._SelectBaseOrderBy, typeof(T).Name, orderName); if (sleepOrder) { outSql = outSql + SQLBaseString._DESC; } return outSql; } /// /// 查询模型数据第一条(有条件) /// /// /// /// /// /// public static string SelectOrderFirst(this IDbConnection con, IEnumerable> fieldKeyList, string sql = "") where T : class { fieldKeyList.ToList().ForEach(m => { m.Value = m.FieldName + "='" + m.Value; }); var outSql = string.Empty; var fieldString = string.Join(SQLBaseString._AND, fieldKeyList.ToList().Select(m => m.Value).ToArray()); if (string.IsNullOrWhiteSpace(sql)) { outSql = string.Format(SQLString._SelectBaseFirst, typeof(T).Name, fieldString); } else { outSql = string.Format(SQLString._SelectBaseFirst, string.Format(SQLBaseString._INCLUDE_TEMP_VIEW, sql), fieldString); } return outSql; } /// /// 查询模型数据第一条(无条件) /// /// /// /// /// /// public static string SelectOrderFirst(this IDbConnection con, string orderName, bool sleepOrder = false) { var outSql = string.Format(SQLString._SelectBaseFirstOrderBy, typeof(T).Name, orderName); if (sleepOrder) { outSql = outSql + SQLBaseString._DESC; } return outSql; } /// /// 查询指定单一条件数据 /// /// /// /// /// /// public static string SelectSQL(this IDbConnection con, string fieldName, string value) where T : class { var outSql = string.Format(SQLString._SelectIdFirstSQLA, typeof(T).Name, fieldName, value); return outSql; } /// /// 分页查询 /// /// /// /// /// /// public static string SelectPage(this IDbConnection con, string sql, string orderByName, int pageSize, int pageIndex, bool sleepOrder = false) where T : class { var outSql = string.Format(SQLString._SelectPageBase, sql, orderByName, sleepOrder ? "DESC" : "", pageSize * (pageIndex - 1), pageSize); return outSql; } /// /// 分页查询 /// /// /// /// /// /// public static string SelectPage(this IDbConnection con, string orderByName, int pageSize, int pageIndex, string whereSQL = "", bool sleepOrder = false) where T : class { var sql = string.Format(SQLString._SelectSQLA, typeof(T).Name, whereSQL); var outSql = string.Format(SQLString._SelectPageBase, sql, orderByName, sleepOrder ? "DESC" : "", pageSize * (pageIndex - 1), pageSize); return outSql; } #endregion #region count /// /// 统计记录总数 /// /// /// /// /// public static string Count(this IDbConnection con, string parms) where T : class { var outSql = string.Format(SQLString._CountBase, typeof(T).Name, parms); return outSql; } #endregion } #endregion #region Dynamic查询 /// /// Dynamic查询 /// public sealed class DynamicQuery { #region 获取插入语句结果DataTable /// /// 获取插入语句结果DataTable /// /// /// /// /// /// public static void GetInsertQuery(string tableName, DataTable item, string outFieldName, IEnumerable filterNames) { for (int i = 0; i < item.Rows.Count; i++) { var fieldList = new List(); var valueList = new List(); } } #endregion #region 获取插入语句结果 /// /// 获取插入语句结果 /// /// /// /// /// /// /// public static string GetInsertQuery(string tableName, object item, string outFieldName, IEnumerable filterNames) { var props = item.GetType().GetProperties(); var columns = props.Where(m => m.GetValue(item, null) != null). //去除时间类型中的默认值 Where(m => m.GetValue(item, null).ToString() != DateTime.MinValue.ToString() //&& (m.GetValue(item, null).GetType() = Type.GetType("System.DateTime", true, true) ).Select(p => "[" + p.Name + "]").ToList(); var values = new List(); if (filterNames != null) { foreach (var items in filterNames) { columns = columns.Where(s => s != "[" + items + "]").ToList(); } foreach (PropertyInfo detail in props) { if (columns.Where(m => m.ToString() == "[" + detail.Name + "]").Any()) { values.Add(item.GetType().GetProperty(detail.Name).GetValue(item, null).ToString()); } } if (string.IsNullOrWhiteSpace(outFieldName)) { return string.Format(SQLString._InsertBase, tableName, string.Join(",", columns), "'" + string.Join("','", values) + "'"); } return string.Format(SQLString._InsertOutFirstFieldBase, tableName, string.Join(",", columns), "'" + string.Join("','", values) + "'", outFieldName); } else { foreach (PropertyInfo detail in props) { if (item.GetType().GetProperty(detail.Name).GetValue(item, null) != null) { values.Add(item.GetType().GetProperty(detail.Name).GetValue(item, null).ToString()); } } if (string.IsNullOrWhiteSpace(outFieldName)) { return string.Format(SQLString._InsertBase, tableName, string.Join(",", columns), "'" + string.Join("','", values) + "'"); } return string.Format(SQLString._InsertOutFirstFieldBase, tableName, string.Join(",", columns), "'" + string.Join("','", values) + "'", outFieldName); } } #endregion #region 获取删除语句结果 /// /// 获取删除语句结果 /// /// /// /// public static string GetDeleteQuery(string tableName, string whereParm) { if (!string.IsNullOrWhiteSpace(tableName)) { return string.Format(SQLString._DeleteBaseA, tableName, whereParm); } else { return string.Empty; } } #endregion #region 获取删除表语句结果 /// /// 获取删除表语句结果 /// /// /// public static string GetDropTableQuery(string tableName) { if (!string.IsNullOrWhiteSpace(tableName)) { return string.Format(SQLString._DropBase, tableName); } else { return string.Empty; } } #endregion #region 获取更新语句结果 /// /// 获取更新语句结果 /// /// /// /// /// public static string GetUpdateQuery(string tableName, object item, string identityFieldName, string noUpdateIdentityFieldNames) { var props = item.GetType().GetProperties(); var columns = props.Where(s => s.Name != identityFieldName && !s.Name.Equals(identityFieldName) && !s.Name.Equals(noUpdateIdentityFieldNames) && //TODO 这里只支持一个不更新字段名称,后期改 s.GetValue(item, null) != null && ((s.GetValue(item, null).ToString() != DateTime.MinValue.ToString() && s.GetValue(item, null).GetType() == Type.GetType("System.DateTime", true, true)) || s.GetValue(item, null).GetType() != Type.GetType("System.DateTime", true, true)) ).ToArray(); var parameters = columns.Select(s => "[" + s.Name + "]" + SQLBaseString._TO + "'" + s.GetValue(item, null) + "'").ToList(); var whereParameter = props.Where(s => s.Name.ToLower() == identityFieldName.ToLower()).FirstOrDefault(); return string.Format(SQLString._UpdateBase, tableName, string.Join(",", parameters), string.Format("[" + identityFieldName + "]" + "='" + whereParameter.GetValue(item, null)) + "'" ); } public static string GetUpdateQuery(string tableName, object item, string identityFieldName) { var props = item.GetType().GetProperties(); var columns = props.Where(s => s.Name != identityFieldName && !s.Name.Equals(identityFieldName) && //TODO 这里只支持一个不更新字段名称,后期改 s.GetValue(item, null) != null && ((s.GetValue(item, null).ToString() != DateTime.MinValue.ToString() && s.GetValue(item, null).GetType() == Type.GetType("System.DateTime", true, true)) || s.GetValue(item, null).GetType() != Type.GetType("System.DateTime", true, true)) ).ToArray(); var parameters = columns.Select(s => "[" + s.Name + "]" + SQLBaseString._TO + "'" + s.GetValue(item, null) + "'").ToList(); var whereParameter = props.Where(s => s.Name.ToLower() == identityFieldName.ToLower()).FirstOrDefault(); return string.Format("UPDATE {0} SET {1} ", tableName, string.Join(",", parameters), string.Format("[" + identityFieldName + "]" + "='" + whereParameter.GetValue(item, null)) + "'" ); } #endregion #region 获取更新语句结果Value /// /// 获取更新语句结果Value /// /// /// /// /// public static string GetUpdateQuery(string tableName, object item, string value, string identityFieldName, string noUpdateIdentityFieldNames) { var props = item.GetType().GetProperties(); var columns = props.Where(s => s.Name != identityFieldName && !s.Name.Equals(identityFieldName) && !s.Name.Equals(noUpdateIdentityFieldNames) && //TODO 这里只支持一个不更新字段名称,后期改 s.GetValue(item, null) != null && (s.GetValue(item, null).ToString() != DateTime.MinValue.ToString() && s.GetValue(item, null).GetType() != Type.GetType("System.DateTime", true, true)) ).ToArray(); var parameters = columns.Select(s => "[" + s.Name + "]" + SQLBaseString._TO + "'" + s.GetValue(item, null) + "'").ToList(); return string.Format(SQLString._UpdateBase, tableName, string.Join(",", parameters), string.Format("[" + identityFieldName + "]" + "='" + value) + "'" ); } #endregion #region 获取Where语句段 /// /// 获取Where语句段 /// /// /// public static string GetWhereSQL(IEnumerable fieldKeyList) { if (fieldKeyList == null) { return ""; } var paramList = new List(); fieldKeyList.Select(m => m.GroupIndex).Distinct().ToList().ForEach(index => { var parmItem = new List(); fieldKeyList.Where(m => m.GroupIndex == index).ToList().ForEach(m => { switch (m.FileType.Value) { case EnumCSharpPropertyType.BOOL: case EnumCSharpPropertyType.BOOLEAN: parmItem.Add(string.Format("{3} {0} {2} {1}", m.FieldName, Convert.ToInt32(m.Value), m.Operation, m.WhereItemType.ToString())); break; case EnumCSharpPropertyType.INT: case EnumCSharpPropertyType.INT16: case EnumCSharpPropertyType.INT32: case EnumCSharpPropertyType.DECIMAL: case EnumCSharpPropertyType.DOUBLE: case EnumCSharpPropertyType.FLOAT: parmItem.Add(string.Format("{2} {0} = {1}", m.FieldName, m.Value, m.WhereItemType.ToString())); break; case EnumCSharpPropertyType.BYTE: break; case EnumCSharpPropertyType.DATE: case EnumCSharpPropertyType.DATETIME: case EnumCSharpPropertyType.STRING: switch (m.Operation) { //包含和不包含有特殊意思在 case DBOperationString._ContainIn: parmItem.Add(string.Format("{2} {1} {0}", string.Format(DBOperationString._ContainIn, m.Value), m.FieldName, m.WhereItemType.ToString())); break; case DBOperationString._NoContainIn: parmItem.Add(string.Format("{2} {1} {0}", string.Format(DBOperationString._NoContainIn, m.Value), m.FieldName, m.WhereItemType.ToString())); break; case DBOperationString._In: parmItem.Add(string.Format("{2} {1} {0}", string.Format(DBOperationString._In, m.Value), m.FieldName, m.WhereItemType.ToString())); break; case DBOperationString._NoEqual: parmItem.Add(string.Format("{2} {0} !='{1}'", m.FieldName, m.Value, m.WhereItemType.ToString())); break; default: parmItem.Add(string.Format("{2} {0} ='{1}'", m.FieldName, m.Value, m.WhereItemType.ToString())); break; } break; }; }); paramList.Add("(1=1 " + string.Join(" ", parmItem) + ")"); }); return string.Join(" AND ", paramList); } #endregion } #endregion #region private /// /// 动态工具 /// public static class DynamicUtil { #region 转换扩展 /// /// 转换模型 /// /// /// public static OperateResultInfo GetConvertDataTableMapper(this T tModels) { var tList = new List(); tList.Add(tModels); return new OperateResultInfo { AffectedRows = 0, Data = ModelsToDataTable(tList), Message = string.Empty, Status = OperateStatus.Success, }; } /// /// 转换List模型 /// /// /// public static OperateResultInfo GetConvertDataTableMapper(this List tModels) { return new OperateResultInfo { AffectedRows = 0, Data = ModelsToDataTable(tModels), Message = string.Empty, Status = OperateStatus.Success, }; } /// /// 模型转换成Datatable /// /// /// /// public static DataTable ModelsToDataTable(IEnumerable collection) { var props = typeof(T).GetProperties(); var dt = new DataTable(); dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray()); if (collection.Count() > 0) { for (int i = 0; i < collection.Count(); i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in props) { object obj = pi.GetValue(collection.ElementAt(i), null); tempList.Add(obj); } object[] array = tempList.ToArray(); dt.LoadDataRow(array, true); } } return dt; } #endregion } #endregion }