static void LoadViewSchema(object para) { Dictionary <string, string> fileList = SqlCode.FileList; if (fileList != null && fileList.Count > 0) { foreach (KeyValuePair <string, string> item in fileList) { if (item.Key.StartsWith("V_") && item.Value.IndexOf('@') == -1)//视图文件,仅处理无参数的。 { string sql = ""; if (item.Value.Contains(":\\"))//存档的是文件路径 { sql = SqlCode.GetCode(item.Key); } else { sql = item.Value; } DBTool.GetColumns(sql, GetConn(sql)); } } } }
internal static bool Update <T>(this DbConnection conn, T obj, int?commandTimeout = null) where T : BaseDBModel { if (obj.GetDBModel_ChangeList().Count == 0) { throw new Exception("没有修改列"); } if (obj.GetDBModel_PKCols().Count == 0) { throw new Exception("没有主键"); } var elst = obj.GetDBModel_PKCols().AddRange(obj.GetDBModel_ExcludeColsForUpdate()); var updateList = obj.GetDBModel_ChangeList().Where(m => m != obj.GetDBModel_IncrementCol() && !elst.Contains(m)).ToList(); var sql = $"UPDATE [{DBTool.GetTableName(obj)}] SET {GetSql(updateList, ",")} WHERE {GetSql(obj.GetDBModel_PKCols(), "AND")}"; try { return(conn.Execute(sql: sql, param: obj, commandTimeout: commandTimeout) > 0); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + JsonHelper.ToJSON(obj) + ExceptionTool.ToString(e)); throw; } }
private void TestTranDelete(bool isCommit) { var repository = GetRepository(); var query = QueryFactory.Create <ProductSaleByDayNSEntity>(); query.And(m => !m.DataSource.Contains("修改")); query.OrderByDescing(m => m.StatisticalDate); query.StarSize = new Random().Next(5); query.Rows = 1; var model = repository.GetPaging(query).ToList()[0]; using (var tran = DBTool.BeginTransaction()) { repository.Delete(model); var deleteCount = repository.Delete(m => m.DataSource == "测试来源批量修改"); Assert.True(deleteCount > 0); if (isCommit) { tran.Complete(); } } if (isCommit) { var delModel = repository.Get(new ProductSaleByDayNSEntity { SysNo = model.SysNo }); Assert.IsNull(delModel); } else { var delModel = repository.Get(new ProductSaleByDayNSEntity { SysNo = model.SysNo }); Assert.IsNotNull(delModel); } }
internal static int Update <T>(this DbConnection conn, T obj, IQuery <T> where, int?commandTimeout = null) where T : BaseDBModel { if (obj.GetDBModel_ChangeList().Count == 0) { throw new Exception("没有修改列"); } var elst = obj.GetDBModel_PKCols().AddRange(obj.GetDBModel_ExcludeColsForUpdate()); var updateList = obj.GetDBModel_ChangeList().Where(m => m != obj.GetDBModel_IncrementCol() && !elst.Contains(m)).ToList(); var sql = new StringBuilder($"UPDATE [{DBTool.GetTableName(obj)}] SET {GetSql(updateList, ",")} WHERE 1=1"); DynamicParameters dynamicParameters = SetWhereSql(where, sql); dynamicParameters.AddDynamicParams(obj); try { return(conn.Execute(sql: sql.ToString(), param: dynamicParameters, commandTimeout: commandTimeout)); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + JsonHelper.ToJSON(obj) + ToIQueryJSON(dynamicParameters, where) + ExceptionTool.ToString(e)); throw; } }
public static bool CheckSysAutoCacheTable() { if (!HasAutoCacheTable && !string.IsNullOrEmpty(AppConfig.Cache.AutoCacheConn)) { string AutoCacheConn = AppConfig.Cache.AutoCacheConn; if (DBTool.TestConn(AutoCacheConn)) { HasAutoCacheTable = DBTool.Exists(KeyTableName, AutoCacheConn); //检测数据是否存在表 if (!HasAutoCacheTable) { MDataColumn mdc = new MDataColumn(); mdc.Add("CacheKey", System.Data.SqlDbType.NVarChar, false, false, 200, true, null); mdc.Add("CacheTime", System.Data.SqlDbType.BigInt, false, false, -1); HasAutoCacheTable = DBTool.CreateTable(KeyTableName, mdc, AutoCacheConn); if (!HasAutoCacheTable) //若创建失败,可能并发下其它进程创建了。 { HasAutoCacheTable = DBTool.Exists(KeyTableName, AutoCacheConn); //重新检测表是否存在。 } } } } return(HasAutoCacheTable); }
private void insertCheckDetail(CheckBillBody ckbody, SqlTransaction trans) { string sql = @"INSERT INTO [CheckBillBody] ([HeadId] ,[ProductID] ,[ProductName] ,[CategoryID] ,[Price] ,[Place] ,[NowNum] ,[RealNum]) VALUES (@HeadId ,@ProductID ,@ProductName ,@CategoryID ,@Price ,@Place ,@NowNum ,@RealNum)"; SqlParameter[] spvalues = DBTool.GetSqlPm(ckbody); SqlHelper.ExecuteNonQuery(trans, CommandType.Text, sql, spvalues); }
public IList <TransferLog> GetTransferLogListByProc(SqlConnection conn, SqlParameter[] paras, string strProcedureName) { IList <TransferLog> lLog = new List <TransferLog>(); DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(); cmd.Parameters.AddRange(paras); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = strProcedureName; cmd.Connection = conn; try { SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); if (ds.Tables.Count > 0) { lLog = DBTool.GetListFromDatatable <TransferLog>(ds.Tables[0]); } } catch { } return(lLog); }
protected override bool IsExistsDbName(string dbName) { return(DBTool.TestConn(GetNewConn(dbName))); }
/// <summary> /// 验证基础数据(数据类型、长度、是否为Null) /// </summary> /// <returns></returns> public static bool ValidateData(MDataTable dt, MDataRow info) { bool result = true; string[] tables = null; List <string> requiredList = new List <string>();//必填项表。 if (info != null) { tables = info.Get <string>(Config_Excel.TableNames, string.Empty).Split(','); MDataTable dtRequired = GetExcelInfo(info.Get <string>(0));//必填项表。 if (dtRequired != null && dtRequired.Rows.Count > 0) { dtRequired = dtRequired.Select(Config_ExcelInfo.IsRequired + "=1"); if (dtRequired != null && dtRequired.Rows.Count > 0) { foreach (var row in dtRequired.Rows) { requiredList.Add(row.Get <string>(Config_ExcelInfo.TableName) + row.Get <string>(Config_ExcelInfo.Field)); } } } } else { tables = dt.TableName.Split(','); } bool isOK = false; foreach (var table in tables)//重置列头。 { MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(table)); foreach (var cs in dt.Columns) { string[] items = cs.ColumnName.Split('.'); if (cs.TableName == table) { int index = mdc.GetIndex(items[items.Length - 1]); if (index > -1) { isOK = true;//至少需要一个列对应上,若没有,则模板错误 cs.SqlType = mdc[index].SqlType; cs.IsCanNull = mdc[index].IsCanNull; if (requiredList.Contains(table + mdc[index].ColumnName))//要求必填 { cs.IsCanNull = false; } cs.MaxSize = mdc[index].MaxSize; } } } } if (!isOK) { return(false); } foreach (var row in dt.Rows) { StringBuilder sb = new StringBuilder(); foreach (var cell in row) { if (!string.IsNullOrEmpty(cell.Struct.TableName)) { string columnName = string.IsNullOrEmpty(cell.Struct.Description) ? cell.Struct.ColumnName : cell.Struct.Description; if (!cell.Struct.IsCanNull && cell.IsNullOrEmpty) { sb.AppendFormat("[{0}]{1}", columnName, LangConst.CantBeEmpty); cell.State = -1; } else if (cell.Struct.MaxSize != -1 && cell.ToString().Length > cell.Struct.MaxSize && cell.Struct.SqlType != System.Data.SqlDbType.Bit) { sb.AppendFormat("[{0}]{1}{2}。", columnName, LangConst.SizeOver, cell.Struct.MaxSize); cell.State = -1; } else if (!cell.FixValue()) { sb.AppendFormat("[{0}]{1}。", columnName, LangConst.DataTypeError); cell.State = -1; } } } if (sb.Length > 0) { result = false; row.Set(LangConst.ErrorInfo, row.Get <string>(LangConst.ErrorInfo) + sb.ToString()); } } return(result); }
/// <summary> /// 获取授权Token(手机APP登陆调用此方法获取Token为登陆凭证) /// </summary> internal static string GetAuthToken(string userName, string password, out string errMsg) { string token = string.Empty; errMsg = ""; using (MAction action = new MAction(user.TableName)) { string status = ""; if (action.Data.Columns.Contains(user.Status)) { status += user.Status + "=1 and "; } string where = string.Empty; if (action.DataBaseType == DataBaseType.Txt || action.DataBaseType == DataBaseType.Xml) { where = status + user.UserName + string.Format("='{0}'", userName); } else { action.SetPara("UserName", userName, System.Data.DbType.String); string other = ""; if (action.Data.Columns.Contains(user.UserName)) { other = DBTool.Keyword(user.UserName, action.DataBaseType) + "=@UserName"; } if (action.Data.Columns.Contains(user.Mobile)) { if (other != "") { other += " or "; } other += DBTool.Keyword(user.Mobile, action.DataBaseType) + "=@UserName"; } if (action.Data.Columns.Contains(user.Email)) { if (other != "") { other += " or "; } other += DBTool.Keyword(user.Email, action.DataBaseType) + "=@UserName"; } where = status + string.Format("({0})", other); } if (action.Fill(where)) { if (action.Data.Columns.Contains(user.PasswordExpireTime) && action.Get <DateTime>(user.PasswordExpireTime, DateTime.MaxValue) < DateTime.Now) { errMsg = AuthConst.PasswordExpired; } else { string pwd = action.Get <string>(user.Password); if (password == EncryptHelper.Decrypt(pwd)) { string userID = action.Get <string>(action.Data.PrimaryCell.ColumnName); string fullName = action.Get <string>(user.FullName, userName); if (!pwd.EndsWith("=2") && AppConfig.EncryptKey != "") { action.Set(user.Password, EncryptHelper.Encrypt(password)); //重新加密密码 action.Update(where); //更新信息。 } //获取角色名称 string roleIDs = action.Get <string>(user.RoleID, "").Replace(',', '_'); token = EncryptHelper.Encrypt(DateTime.Now + "," + userID + "," + userName + "," + fullName + "," + roleIDs); } else { errMsg = AuthConst.PasswordError; } } } else { errMsg = AuthConst.UserNotExist; } } return(token); }
/// <summary> /// 批量更新或插入。 /// </summary> /// <param name="dt"></param> /// <param name="excelRow"></param> /// <returns></returns> public static bool AcceptChanges(MDataTable dt, MDataRow excelRow, string objName = null) { if (excelRow == null) { MDataTable dtImportUnique = GridConfig.GetList(objName, GridConfig.SelectType.ImportUnique); string[] names = null; if (dtImportUnique != null && dtImportUnique.Rows.Count > 0) { names = new String[dtImportUnique.Rows.Count]; for (int i = 0; i < dtImportUnique.Rows.Count; i++) { names[i] = dtImportUnique.Rows[i].Get <string>(Config_Grid.Field); } } dt.Conn = DBTool.GetTableInfo(dt.TableName).DBInfo.ConnName; if (names != null || dt.Columns.FirstPrimary.IsAutoIncrement || dt.Columns.FirstPrimary.IsPrimaryKey) { return(dt.AcceptChanges(AcceptOp.Auto, null, names)); } return(dt.AcceptChanges(AcceptOp.Insert, null, null)); } bool result = true; //获取相关配置 string[] tables = excelRow.Get <string>(Config_Excel.TableNames).Split(','); MDataTable configTable = GetExcelInfo(excelRow.Get <string>(Config_Excel.ExcelID)); Dictionary <string, string> rowPrimaryValue = new Dictionary <string, string>(); //存档每个表每行的主键值。 Dictionary <string, string> wherePrimaryValue = new Dictionary <string, string>(); //存档where条件对应的主键值。 int acceptType = excelRow.Get <int>(Config_Excel.AcceptType); using (MAction action = new MAction(tables[0])) { action.SetAopState(AopOp.CloseAll); action.BeginTransation(); AppConfig.Debug.OpenDebugInfo = false; IExcelConfig excelConfigExtend = ExcelConfigFactory.GetExcelConfigExtend(); foreach (var table in tables) { GC.Collect();//后面的Fill查询代码循环上万次会增长太多内存,提前调用,能降低内存。 action.ResetTable(table); for (int i = 0; i < dt.Rows.Count; i++) { action.Data.Clear(); var row = dt.Rows[i]; foreach (var cell in row) //遍历所有数据行 { if (cell.Struct.TableName != null && cell.Struct.TableName.ToLower() == table.ToLower()) //过滤出属于本表的字段。 { string[] items = cell.ColumnName.Split('.'); string columnName = items[items.Length - 1]; action.Set(columnName, cell.Value); } } #region 检测是否需要插入外键。 MDataTable foreignTable = configTable.FindAll("TableName='" + table + "' and IsForeignkey=1"); if (foreignTable != null) { foreach (var foreignRow in foreignTable.Rows) { string formatter = foreignRow.Get <string>("Formatter", "").Trim('.'); string fTableName = foreignRow.Get <string>("ForeignTable"); if (string.IsNullOrEmpty(formatter)) { //获取主键外值键 string key = fTableName + i; if (rowPrimaryValue.ContainsKey(key)) { string value = rowPrimaryValue[key]; action.Set(foreignRow.Get <string>("Field"), value); } } else // 从其它自定义列取值。 { MDataCell cell = row[formatter]; cell = cell ?? row[fTableName + "." + formatter]; if (cell != null) { action.Set(foreignRow.Get <string>("Field"), cell.Value); } } } foreignTable = null; } #endregion #region //获取唯一联合主键,检测是否重复 string where = string.Empty; MDataRowCollection rowList = configTable.FindAll("TableName='" + table + "' and IsUnique=1"); if (rowList != null && rowList.Count > 0) { bool isUniqueOr = excelRow.Get <bool>(Config_Excel.WhereType); List <MDataCell> cells = new List <MDataCell>(); StringBuilder errText = new StringBuilder(); int errorCount = 0; foreach (var item in rowList) { var cell = action.Data[item.Get <string>(Config_ExcelInfo.Field)]; if (cell != null) { if (cell.IsNullOrEmpty) // 唯一主键是必填写字段 { errorCount++; errText.Append("[" + LangConst.The + "" + (i + 1) + LangConst.Row + "]:" + cell.Struct.ColumnName + "[" + cell.Struct.Description + "]" + LangConst.CantBeEmpty + "!\r\n"); } else { cells.Add(cell); } } } if (errorCount > 0) { if (!isUniqueOr || errorCount == rowList.Count) { result = false; dt.DynamicData = new Exception(errText.ToString()); goto err; } } MDataCell[] item2s = cells.ToArray(); where = action.GetWhere(!isUniqueOr, item2s); item2s = null; rowList = null; } if (!string.IsNullOrEmpty(where)) { MDataRow data = action.Data.Clone(); action.SetSelectColumns(action.Data.PrimaryCell.ColumnName); if (action.Fill(where))//根据条件查出主键id (数据被清空) { string key = table + where; if (wherePrimaryValue.ContainsKey(key)) { rowPrimaryValue.Add(table + i, wherePrimaryValue[key]);//记录上一个主键值。 } else { rowPrimaryValue.Add(table + i, action.Get <string>(action.Data.PrimaryCell.ColumnName)); //记录上一个主键值。 } action.Data.LoadFrom(data, RowOp.IgnoreNull, false); //还原数据。 if (action.Data.GetState() == 2 && acceptType != 1) //排除掉仅插入选项 { ExcelResult eResult = excelConfigExtend.BeforeUpdate(action.Data, row); if (eResult == ExcelResult.Ignore || (eResult == ExcelResult.Default && action.Update(where))) { continue;//已经存在了,更新,准备下一条。 } else { result = false; dt.DynamicData = new Exception("[" + LangConst.The + (i + 1) + LangConst.Row + "]:" + action.DebugInfo); goto err; } } else { continue;//已经存在了,同时没有可更新字段 } } else if (action.RecordsAffected == -2)//产生错误信息,发生异常 { result = false; dt.DynamicData = new Exception("[" + LangConst.The + (i + 1) + LangConst.Row + "]:" + action.DebugInfo); goto err; } } #endregion if (action.Data.GetState() == 0 || acceptType == 2) //仅更新则跳过插入 { continue; //没有可映射插入的列。 } //插入前,调用函数(插入特殊主键等值) string errMsg; ExcelResult excelResult = excelConfigExtend.BeforeInsert(action.Data, row, out errMsg); if (excelResult == ExcelResult.Ignore) { continue; } if (excelResult == ExcelResult.Error || !action.Insert(InsertOp.ID)) { result = false; action.RollBack(); if (string.IsNullOrEmpty(errMsg)) { errMsg = "[" + LangConst.The + (i + 1) + LangConst.Row + "]:" + action.DebugInfo; } dt.DynamicData = new Exception(errMsg); excelConfigExtend.OnInsertError(errMsg, dt); goto err; } //插入后事件(可以触发其它事件) excelConfigExtend.AfterInsert(action.Data, row, i == dt.Rows.Count - 1); string primaryKey = action.Get <string>(action.Data.PrimaryCell.ColumnName); rowPrimaryValue.Add(table + i, primaryKey);//记录上一个主键值。 if (!wherePrimaryValue.ContainsKey(table + where)) { wherePrimaryValue.Add(table + where, primaryKey); } } } err: action.EndTransation(); excelConfigExtend.Dispose(); } return(result); }
static void Start() { bool result = DBTool.TestConn(AppConfig.DB.DefaultConn);//检测数据库链接是否正常 OutMsg("数据库链接:" + result); OutMsg("-----------------------------------------"); string databaseName; Dictionary <string, string> tables = DBTool.GetTables(AppConfig.DB.DefaultConn, out databaseName);//读取所有表 if (tables != null) { OutMsg("数据库:" + databaseName); foreach (KeyValuePair <string, string> item in tables) { OutMsg("表:" + item.Key + " 说明:" + item.Value); MDataColumn mdc = DBTool.GetColumns(item.Key);//读取所有列 foreach (MCellStruct ms in mdc) { OutMsg(" 列:" + ms.ColumnName + " SqlType:" + ms.SqlType); } } } OutMsg("-----------------------------------------"); string newTableName = "A18";// +DateTime.Now.Second; DalType dalType; result = DBTool.ExistsTable(newTableName, AppConfig.DB.DefaultConn, out dalType);//检测表是否存在 OutMsg("表 " + newTableName + (result ? "存在" : "不存在") + " 数据库类型:" + dalType); OutMsg("-----------------------------------------"); if (result) { result = DBTool.DropTable(newTableName); OutMsg("表 " + newTableName + " 删除?" + result); OutMsg("-----------------------------------------"); } MDataColumn newMdc = new MDataColumn(); newMdc.Add("ID", System.Data.SqlDbType.Int); newMdc.Add("Name", System.Data.SqlDbType.NVarChar); result = DBTool.CreateTable(newTableName, newMdc); OutMsg("表 " + newTableName + " 创建?" + result); OutMsg("-----------------------------------------"); newMdc[1].ColumnName = "UserName"; newMdc[1].AlterOp = AlterOp.Rename; //将新创建的表name => username newMdc.Add("Password"); newMdc[2].AlterOp = AlterOp.AddOrModify; // 新增列 Password result = DBTool.AlterTable(newTableName, newMdc); OutMsg("表 " + newTableName + " 修改结构?" + result); OutMsg("-----------------------------------------"); OutMsg("------------------其它操作-------------------"); dalType = DBTool.GetDalType("txt path={0}"); OutMsg("数据库类型为: " + dalType); OutMsg("-----------------------------------------"); OutMsg(DBTool.Keyword("表关键字", DalType.MsSql));//DBTool.NotKeyword 则取消 OutMsg(DBTool.Keyword("表关键字", DalType.Oracle)); OutMsg(DBTool.Keyword("表关键字", DalType.MySql)); OutMsg(DBTool.Keyword("表关键字", DalType.SQLite)); string changeDataType = DBTool.GetDataType(newMdc[0], DalType.Access, string.Empty); OutMsg("数据类型为: " + changeDataType); OutMsg("-----------------------------------------"); string formatValue = DBTool.FormatDefaultValue(DalType.Access, "[#GETDATE]", 1, System.Data.SqlDbType.DateTime); OutMsg("Access的日期数据类型为: " + formatValue); OutMsg("-----------------------------------------"); }
private IJoinQuery <TResult> Join <TR, TKey, TResult>(string type, IQuery <TR> rightQuery, Expression <Func <T, TKey> > leftKeySelector, Expression <Func <TR, TKey> > rightKeySelector, Expression <Func <T, TR, TResult> > resultSelector) where TR : BaseDBModel, new() { var dynamicParameters = new DynamicParameters(); var left = new JoinExpression(leftKeySelector, new Dictionary <string, string> { { "", "t1" } }, dynamicParameters, DBModel.GetDBModel_SqlProvider()); var right = new JoinExpression(rightKeySelector, new Dictionary <string, string> { { "", "t2" } }, dynamicParameters, DBModel.GetDBModel_SqlProvider()); StringBuilder sqlJoin = new StringBuilder(); foreach (var v in left.JoinDic) { if (sqlJoin.Length > 0) { sqlJoin.Append(" AND "); } sqlJoin.Append("("); sqlJoin.Append(v.Value); sqlJoin.Append("="); sqlJoin.Append(right.JoinDic[v.Key]); sqlJoin.Append(")"); } var joinStr = $"{DBTool.GetTableName(DBModel)} t1 {DBTool.GetTableWith(this)} {type} JOIN {DBTool.GetTableName(rightQuery.DBModel)} t2 {DBTool.GetTableWith(rightQuery)} ON {sqlJoin}"; var sel = new JoinResultMapExpression(resultSelector, new Dictionary <string, string> { { "", "t1" } }, "t2", dynamicParameters, DBModel.GetDBModel_SqlProvider()); StringBuilder sqlWhere = new StringBuilder(); var where = new WhereExpression(this.WhereExpression, "t1", dynamicParameters, DBModel.GetDBModel_SqlProvider()); if (!string.IsNullOrEmpty(where.SqlCmd)) { sqlWhere.Append(where.SqlCmd); } where = new WhereExpression(rightQuery.WhereExpression, "t2", dynamicParameters, DBModel.GetDBModel_SqlProvider()); if (!string.IsNullOrEmpty(where.SqlCmd)) { sqlWhere.Append(where.SqlCmd); } return(new JoinQueryInfo <TResult>(DBModel, joinStr, 2, sel.MapList, sqlWhere.ToString(), dynamicParameters)); }
/// <summary> /// 读取数据库所有表 /// </summary> /// <param name="key">关键字</param> /// <param name="filter">过滤条件值</param> /// <returns></returns> public static MDataTable Get(string key, string filter) { MDataTable dt = null; SortedDictionary <string, string> newDic = new SortedDictionary <string, string>(); switch (key) { case "C_SYS_Table": if (!string.IsNullOrEmpty(filter)) // 有过滤条件 { string[] items = filter.Split(','); if (items.Length == 1 && items[0].EndsWith("Conn")) { if (CrossDb.DbTables.ContainsKey(filter)) { foreach (var item in CrossDb.DbTables[filter]) { newDic.Add(item.Key, item.Key); } } } else { foreach (string item in items) { newDic.Add(item, item); } } } else { foreach (var tableDic in CrossDb.DbTables) { foreach (var item in tableDic.Value) { newDic.Add(item.Key, item.Key); } } } break; case "C_SYS_Column": if (!string.IsNullOrEmpty(filter)) { dt = new MDataTable(key); dt.Columns.Add("value"); dt.Columns.Add("text"); dt.Columns.Add("parent"); string[] items = filter.Split(','); foreach (string item in items) { MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(item)); foreach (MCellStruct ms in mdc) { dt.NewRow(true).Set(0, ms.ColumnName).Set(1, ms.ColumnName).Set(2, item); } } } break; } if (dt == null) { dt = MDataTable.CreateFrom(newDic); dt.Columns[0].ColumnName = "value"; dt.Columns[1].ColumnName = "text"; if (dt.Columns.Count > 2) { dt.Columns[2].ColumnName = "parent"; } } return(dt); }
private static void BuildSingTableEntityText(string tableName, string description, ProjectConfig config, string dbName) { string str = FormatKey(tableName); if (config.MapName) { str = FixName(tableName); } bool flag = config.BuildMode.StartsWith("纯") || config.BuildMode.Contains("DBFast"); try { StringBuilder sb = new StringBuilder(50000); string str2 = string.Format(config.NameSpace, dbName + "DB").TrimEnd(new char[] { '.' }); AppendText(sb, "using System;", new string[0]); AppendText(sb, "using System.ComponentModel.DataAnnotations;", new string[0]); AppendText(sb, "using System.ComponentModel;", new string[0]); if (!config.ForTwoOnly) { AppendText(sb, "using System.ComponentModel.DataAnnotations.Schema;", new string[0]); } AppendText(sb, "", new string[0]); AppendText(sb, "namespace {0}", new string[] { str2 }); AppendText(sb, "{", new string[0]); if (!string.IsNullOrEmpty(description)) { description = description.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " "); AppendText(sb, " /// <summary>", new string[0]); AppendText(sb, " /// {0}", new string[] { description }); AppendText(sb, " /// </summary>", new string[0]); AppendText(sb, " [DisplayName(\"{0}\")]", new string[] { description });//实体表名的指定方法不是这样操作的,需更新,有空再更新 } if (!config.ForTwoOnly) { AppendText(sb, " [Table(\"{0}\")]", str); } AppendText(sb, " public class {0}{1}", new string[] { str + config.EntitySuffix, flag ? "" : " : CYQ.Data.Orm.OrmBase" }); AppendText(sb, " {", new string[0]); if (!flag)//如果是ORM,则进行下面的生成 { AppendText(sb, " public {0}()", new string[] { str + config.EntitySuffix }); AppendText(sb, " {", new string[0]); AppendText(sb, " base.SetInit(this, \"{0}\", \"{1}\");", new string[] { tableName, config.Name }); AppendText(sb, " }", new string[0]); } MDataColumn columns = DBTool.GetColumns(tableName, config.Conn); if (columns.Count > 0) { string name = string.Empty; Type type = null; if (config.ForTwoOnly) // vs2015 模式 { foreach (MCellStruct struct2 in columns) { name = struct2.ColumnName; if (config.MapName) { name = FixName(name); } type = DataType.GetType(struct2.SqlType); string typename = FormatType(type.Name, type.IsValueType, config.ValueTypeNullable); // 详细描述 string Longhand_Description = struct2.Description #region Longhand_Description 处理 .Replace("\r\n", " /// ") .Replace("\r", " /// ") .Replace("\n", " /// ") .Replace(" /// ", "\r\n /// ") ; //移除回车等换行字符串 if (string.IsNullOrEmpty(Longhand_Description)) { Longhand_Description = "[ 无说明描术 ]"; } #endregion // 名称简写 string Shorthand_Description = struct2.Description; #region Shorthand_Description 处理 if (string.IsNullOrEmpty(Shorthand_Description)) { Shorthand_Description = "[ 无说明描术 ]"; } else { Shorthand_Description = Shorthand_Description.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " "); #region // 从零字符开始,取到指定标志字符处 int index = Shorthand_Description.IndexOfAny(new char[] { '(', '(', ':', ':', ' ', ' ', ',', ',', '|', '|', '.', '。' }); index = index == -1 ? Shorthand_Description.Length : index; Shorthand_Description = Shorthand_Description.Substring(0, index); #endregion } #endregion AppendText(sb, " #region [ public {0} {1} {2} ]", new string[] { typename.PadRight(15), name.PadRight(30), Shorthand_Description.PadRight(30) });//添加换行 AppendText(sb, " /// <summary>", new string[0]); AppendText(sb, " /// 私有变量:{0}", new string[] { Longhand_Description }); AppendText(sb, " /// </summary>", new string[0]); AppendText(sb, " private {0} _{1};", new string[] { typename, name }); AppendText(sb, " /// <summary>", new string[0]); AppendText(sb, " /// {0}", new string[] { Longhand_Description }); AppendText(sb, " /// </summary>", new string[0]); AppendText(sb, " [Display(Name = \"{0}\")]", new string[] { Shorthand_Description }); AppendText(sb, " public {0} {1}", new string[] { typename, name }); AppendText(sb, " {", new string[0]); AppendText(sb, " get", new string[0]); AppendText(sb, " {", new string[0]); AppendText(sb, " return _{0};", new string[] { name }); AppendText(sb, " }", new string[0]); AppendText(sb, " set", new string[0]); AppendText(sb, " {", new string[0]); AppendText(sb, " _{0} = value;", new string[] { name }); AppendText(sb, " }", new string[0]); AppendText(sb, " }", new string[0]); AppendText(sb, " #endregion", new string[0]);//添加换行 } } else // 新模式 { foreach (MCellStruct struct3 in columns) { name = struct3.ColumnName; if (config.MapName) { name = FixName(name); } type = DataType.GetType(struct3.SqlType); if (!string.IsNullOrEmpty(struct3.Description)) { // 详细描述 string Longhand_Description = struct3.Description #region Longhand_Description 处理 .Replace("\r\n", " /// ") .Replace("\r", " /// ") .Replace("\n", " /// ") .Replace(" /// ", "\r\n /// ") ; //移除回车等换行字符串 if (string.IsNullOrEmpty(Longhand_Description)) { Longhand_Description = "[ 无说明描术 ]"; } #endregion // 名称简写 string Shorthand_Description = struct3.Description; #region Shorthand_Description 处理 if (string.IsNullOrEmpty(Shorthand_Description)) { Shorthand_Description = "[ 无说明描术 ]"; } else { Shorthand_Description = Shorthand_Description.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " "); #region // 从零字符开始,取到指定标志字符处 int index = Shorthand_Description.IndexOfAny(new char[] { '(', '(', ':', ':', ' ', ' ', ',', ',', '|', '|', '.', '。' }); index = index == -1 ? Shorthand_Description.Length : index; Shorthand_Description = Shorthand_Description.Substring(0, index); #endregion } #endregion struct3.Description = struct3.Description.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " "); AppendText(sb, " /// <summary>", new string[0]); AppendText(sb, " /// {0}", new string[] { Longhand_Description }); AppendText(sb, " /// </summary>", new string[0]); AppendText(sb, " [Display(Name = \"{0}\")]", new string[] { Shorthand_Description }); } if (name.ToUpper() == "ID") { AppendText(sb, " [DataObjectField(true)]"); } AppendText(sb, " public {0} {1} {{ get; set; }}", new string[] { FormatType(type.Name, type.IsValueType, config.ValueTypeNullable), name }); AppendText(sb, ""); } } } sb.Append( @" } }"); File.WriteAllText(config.ProjectPath.TrimEnd(new char[] { '/', '\\' }) + @"\" + str + ".cs", sb.ToString(), Encoding.UTF8); } catch (Exception exception) { CYQ.Data.Log.WriteLogToTxt(exception); } }
internal static long Count <T>(this DbConnection conn, IQuery <T> query, int?commandTimeout = null) where T : BaseDBModel { var sql = new StringBuilder($"SELECT COUNT(1) FROM {query.DBModel.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(query.DBModel)}{query.DBModel.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} {DBTool.GetTableWith(query)} WHERE 1=1 "); DynamicParameters dynamicParameters = SetWhereSql(query, sql, true); try { return(conn.QuerySingleOrDefault <long>(sql: sql.ToString(), param: dynamicParameters, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn))); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + ToIQueryJSON(dynamicParameters, query) + ExceptionTool.ToString(e)); throw; } }
internal static IEnumerable <R> GetList <R, T>(this DbConnection conn, IQuery <T> query, int?commandTimeout = null) where T : BaseDBModel { var sql = new StringBuilder($"SELECT * FROM {query.DBModel.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(query.DBModel)}{query.DBModel.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} {DBTool.GetTableWith(query)} WHERE 1=1 "); DynamicParameters dynamicParameters = SetWhereSql(query, sql); try { var lst = conn.Query <R>(sql: sql.ToString(), param: dynamicParameters, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn)); return(lst); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + ToIQueryJSON(dynamicParameters, query) + ExceptionTool.ToString(e)); throw; } }
/// <summary> /// 初始化状态[继承此基类的实体在构造函数中需调用此方法] /// </summary> /// <param name="entityInstance">实体对象,一般写:this</param> /// <param name="tableName">表名,如:Users</param> /// <param name="conn">数据链接,单数据库时可写Null,或写默认链接配置项:"Conn",或直接数据库链接字符串</param> protected void SetInit(Object entityInstance, string tableName, string conn) { conn = string.IsNullOrEmpty(conn) ? AppConfig.DB.DefaultConn : conn; entity = entityInstance; typeInfo = entity.GetType(); try { if (string.IsNullOrEmpty(tableName)) { tableName = typeInfo.Name; if (tableName.EndsWith(AppConfig.EntitySuffix)) { tableName = tableName.Substring(0, tableName.Length - AppConfig.EntitySuffix.Length); } } string key = tableName + MD5.Get(conn); if (!CacheManage.LocalInstance.Contains(key)) { DalType dal = DBTool.GetDalType(conn); bool isTxtDal = dal == DalType.Txt || dal == DalType.Xml; string errMsg = string.Empty; Columns = DBTool.GetColumns(tableName, conn, out errMsg);//内部链接错误时抛异常。 if (Columns == null || Columns.Count == 0) { if (errMsg != string.Empty) { Error.Throw(errMsg); } Columns = TableSchema.GetColumns(typeInfo); if (!DBTool.ExistsTable(tableName, conn)) { if (!DBTool.CreateTable(tableName, Columns, conn)) { Error.Throw("Create Table Error:" + tableName); } } } else if (isTxtDal)//文本数据库 { if (FieldSource != FieldSource.Data) { MDataColumn c2 = TableSchema.GetColumns(typeInfo); if (FieldSource == FieldSource.BothOfAll) { Columns.AddRange(c2); } else { Columns = c2; } } } if (Columns != null && Columns.Count > 0) { CacheManage.LocalInstance.Add(key, Columns, null, 1440); } } else { Columns = CacheManage.LocalInstance.Get(key) as MDataColumn; } action = new MAction(Columns.ToRow(tableName), conn); if (typeInfo.Name == "SysLogs") { action.SetAopOff(); } action.EndTransation(); } catch (Exception err) { if (typeInfo.Name != "SysLogs") { Log.WriteLogToTxt(err); } throw; } }
public ISelectResult <TResult> Select <TResult>(Expression <Func <T, TResult> > sel) { var dynamicParameters = new DynamicParameters(); var selExp = new JoinSelectExpression(sel, new Dictionary <string, string> { { "", $"{this.DBModel.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}jtmp{this.DBModel.GetDBModel_SqlProvider().GetProviderOption().CloseQuote}" } }, dynamicParameters, DBModel.GetDBModel_SqlProvider()); var selSql = string.Join(",", selExp.QueryColumns).Replace($"{this.DBModel.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}jtmp{this.DBModel.GetDBModel_SqlProvider().GetProviderOption().CloseQuote}.", ""); var sql = new StringBuilder($"SELECT {selSql} FROM {this.DBModel.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(this.DBModel)}{this.DBModel.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} {DBTool.GetTableWith(this)} WHERE 1=1"); var countSql = new StringBuilder($"SELECT COUNT(1) FROM {DBTool.GetTableName(this.DBModel)} {DBTool.GetTableWith(this)} WHERE 1=1"); var whereExp = new WhereExpression(WhereExpression, "", dynamicParameters, DBModel.GetDBModel_SqlProvider()); sql.Append(whereExp.SqlCmd); countSql.Append(whereExp.SqlCmd); if (OrderbyList.Count > 0) { sql.Append($" ORDER BY "); var olst = OrderbyList.Select(m => { var order = new JoinOrderExpression(m.Field, new Dictionary <string, string> { { "", "" } }, dynamicParameters, DBModel.GetDBModel_SqlProvider()); return(order.SqlCmd + " " + m.OrderBy); }); sql.Append(string.Join(",", olst) + " "); } sql.Append(DBModel.GetDBModel_SqlProvider().GetLimit(StarSize, Rows)); var sr = new SelectResult <TResult>(sql.ToString(), countSql.ToString(), dynamicParameters); sr.DBModel = DBModel; return(sr); }
internal static T Get <T>(this DbConnection conn, IQuery <T> query, int?commandTimeout = null) where T : BaseDBModel { var sql = new StringBuilder($"SELECT Top 1 * FROM {query.DBModel.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(query.DBModel)}{query.DBModel.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} {DBTool.GetTableWith(query)} WHERE 1=1 "); DynamicParameters dynamicParameters = SetWhereSql(query, sql); try { var lst = conn.Query <T>(sql: sql.ToString(), param: dynamicParameters, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn)).AsList(); lst.ForEach(m => { m.GetDBModel_ChangeList().Clear(); m.BeginChange(); }); return(lst.FirstOrDefault()); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + ToIQueryJSON(dynamicParameters, query) + ExceptionTool.ToString(e)); throw; } }
public DBToolAdapter() { _dbTool = new DBTool <T>(); }
internal static T Get <T>(this DbConnection conn, T obj, int?commandTimeout = null) where T : BaseDBModel { if (obj.GetDBModel_ChangeList().Count == 0) { throw new LnskyDBException("没有筛选条件"); } var sql = $"SELECT Top 1 * FROM {obj.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(obj)}{obj.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} {DBTool.GetTableWith(obj)} WHERE " + GetSql(obj, obj.GetDBModel_ChangeList(), "AND"); try { var res = conn.QueryFirstOrDefault <T>(sql: sql, param: obj, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn)); res?.GetDBModel_ChangeList().Clear(); return(res); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + JsonHelper.ToJSON(obj) + ExceptionTool.ToString(e)); throw; } }
/// <summary> /// 获取SQl脚本 /// </summary> /// <param name="row"></param> /// <param name="keys"></param> /// <returns></returns> public static string GetSQLScript(MDataRow row, params string[] keys) { DalType dalType = CrossDb.GetDalType(row.TableName); string tableName = DBTool.Keyword(row.TableName, dalType); string where = string.Empty; StringBuilder sb = new StringBuilder(); //sb.AppendFormat("if not EXISTS (select 1 from {0} where ", tableName); //foreach (string key in keys) //{ // if (where != string.Empty) // { // where += " and "; // } // where +=DBTool.Keyword(key,dalType)+"='" + row[key].ToString() + "'"; //} //sb.Append(where); //sb.AppendLine(")\r\nbegin");//Insert sb.AppendFormat("insert into {0}(", tableName);//Insert string columns = string.Empty; foreach (var ct in row.Columns) { columns += DBTool.Keyword(ct.ColumnName, dalType) + ","; } sb.Append(columns.TrimEnd(',') + ") \r\n values("); columns = string.Empty; foreach (var ct in row.Columns) { if (row[ct.ColumnName].IsNull) { columns += "null,"; } else { columns += "'" + row[ct.ColumnName].ToString() + "',"; } } sb.Append(columns.TrimEnd(',') + ")\r\n"); //sb.AppendLine("end"); //sb.AppendLine("else"); //sb.AppendLine("begin");//Update //sb.AppendFormat("update {0} set ", tableName);//Insert //columns = string.Empty; //List<string> items = new List<string>(); //items.AddRange(keys); //foreach (var ct in row.Columns) //{ // if (items.Contains(ct.ColumnName)) // { // continue; // } // if (row[ct.ColumnName].IsNull) // { // columns += DBTool.Keyword(ct.ColumnName,dalType)+ "=null,"; // } // else // { // columns += DBTool.Keyword(ct.ColumnName,dalType) + "='" + row[ct.ColumnName].ToString() + "',"; // } //} //sb.AppendFormat(columns.TrimEnd(',') + " where {0}\r\n", where); //sb.AppendLine("end \r\n"); return(sb.ToString()); }
internal static bool Delete <T>(this DbConnection conn, T obj, int?commandTimeout = null) where T : BaseDBModel { if (obj.GetDBModel_PKCols().Count == 0) { throw new LnskyDBException("没有主键"); } var sql = $"DELETE FROM {obj.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(obj)}{obj.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} WHERE {GetSql(obj, obj.GetDBModel_PKCols(), "AND")}"; try { return(conn.Execute(sql: sql, param: obj, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn)) == 1); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + JsonHelper.ToJSON(obj) + ExceptionTool.ToString(e)); throw; } }
/// <summary> /// 读取数据库所有表 /// </summary> /// <param name="key">关键字</param> /// <param name="filter">过滤条件值</param> /// <returns></returns> public static MDataTable Get(string key, string filter) { MDataTable dt = null; SortedDictionary <string, string> newDic = new SortedDictionary <string, string>(); switch (key) { case "C_SYS_Table": if (!string.IsNullOrEmpty(filter)) // 有过滤条件 { string[] items = filter.Split(','); //指定数据库链接条件 foreach (string item in items) { if (item.EndsWith("Conn")) //当成链接处理 { int dbHash = DBInfo.GetHashCode(item); if (DBTool.DataBases.ContainsKey(dbHash)) { foreach (var table in DBTool.DataBases[dbHash].Tables) { newDic.Add(table.Value.Name, table.Value.Name); } } } else //当成普通表名处理 { newDic.Add(item, item); } } } else { foreach (var db in DBTool.DataBases) { foreach (var table in db.Value.Tables) { newDic.Add(table.Value.Name, table.Value.Name); } } } break; case "C_SYS_Column": if (!string.IsNullOrEmpty(filter)) { dt = new MDataTable(key); dt.Columns.Add("value"); dt.Columns.Add("text"); dt.Columns.Add("parent"); string[] items = filter.Split(','); foreach (string item in items) { MDataColumn mdc = DBTool.GetColumns(item); foreach (MCellStruct ms in mdc) { dt.NewRow(true).Set(0, ms.ColumnName).Set(1, ms.ColumnName).Set(2, item); } } } break; } if (dt == null) { dt = MDataTable.CreateFrom(newDic); dt.Columns[0].ColumnName = "value"; dt.Columns[1].ColumnName = "text"; if (dt.Columns.Count > 2) { dt.Columns[2].ColumnName = "parent"; } } return(dt); }
internal static int Delete <T>(this DbConnection conn, IQuery <T> where, int?commandTimeout = null) where T : BaseDBModel { var sql = new StringBuilder($"DELETE FROM {where.DBModel.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(where.DBModel)}{where.DBModel.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} WHERE 1=1 "); DynamicParameters dynamicParameters = SetWhereSql(where, sql); try { return(conn.Execute(sql: sql.ToString(), param: dynamicParameters, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn))); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + ToIQueryJSON(dynamicParameters, where) + ExceptionTool.ToString(e)); throw; } }
private static void FillTable(string objName, string objCode, MDataTable dt) { Dictionary <string, string> fieldTitleDic = GridConfig.FieldTitle; string errInfo; string tableName = Convert.ToString(CrossDb.GetEnum(objCode)); MDataColumn mdc = DBTool.GetColumns(tableName, null, out errInfo); if (mdc == null || mdc.Count == 0) { if (!string.IsNullOrEmpty(errInfo)) { dt.DynamicData = errInfo; } return; } MCellStruct cell = null; int jointPrimaryCount = mdc.JointPrimary.Count; for (int i = 0; i < mdc.Count; i++) { cell = mdc[i]; MDataRow row = dt.NewRow(); row.Set(Config_Grid.ObjName, objName); row.Set(Config_Grid.Field, cell.ColumnName); row.Set(Config_Grid.Title, fieldTitleDic.ContainsKey(cell.ColumnName) ? fieldTitleDic[cell.ColumnName] : cell.ColumnName); row.Set(Config_Grid.Hidden, (i == 0 && jointPrimaryCount < 2) || i > 25);//超过25个字段,后面的都先隐藏。 row.Set(Config_Grid.OrderNum, (i + 1) * 10); row.Set(Config_Grid.Width, 100); row.Set(Config_Grid.Sortable, i > 0); row.Set(Config_Grid.Import, i > 0); row.Set(Config_Grid.Export, i > 0); row.Set(Config_Grid.Colspan, 1); row.Set(Config_Grid.Rowspan, 1); row.Set(Config_Grid.Edit, i > 0 || jointPrimaryCount > 1); row.Set(Config_Grid.Frozen, i < 4); row.Set(Config_Grid.Align, "center"); string value = DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + (cell.IsCanNull ? ",0" : ",1") + (cell.IsPrimaryKey ? ",1" : ",0"); row.Set(Config_Grid.DataType, value); if (i == 0) { if (jointPrimaryCount < 2) { row.Set(Config_Grid.Formatter, "#"); } } else { switch (DataType.GetGroup(cell.SqlType)) { case 2: row.Set(Config_Grid.Formatter, "dateFormatter"); break; case 3: row.Set(Config_Grid.Formatter, "boolFormatter"); break; default: if (cell.MaxSize > 50) { row.Set(Config_Grid.Formatter, "stringFormatter"); } break; } } dt.Rows.Add(row); } }
internal static void Add <T>(this DbConnection conn, T obj, int?commandTimeout = null) where T : BaseDBModel { if (obj.GetDBModel_ChangeList().Count == 0) { throw new LnskyDBException("没有修改列"); } var sql = $"INSERT INTO {obj.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(obj)}{obj.GetDBModel_SqlProvider().GetProviderOption().CloseQuote}({string.Join(',', obj.GetDBModel_ChangeList())}) VALUES(@{string.Join(",@", obj.GetDBModel_ChangeList())});"; try { if (!string.IsNullOrEmpty(obj.GetDBModel_IncrementCol())) { sql += obj.GetDBModel_SqlProvider().GetSelectIncrement(); var v = conn.ExecuteScalar <int>(sql: sql, param: obj, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn)); obj.SetIncrementValue(v); } else { conn.Execute(sql: sql, param: obj, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn)); } obj.GetDBModel_ChangeList().Clear(); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + JsonHelper.ToJSON(obj) + ExceptionTool.ToString(e)); throw; } }
public void TestTearDown() { DBTool.CloseConnections(); }
internal static List <T> GetAll <T>(this DbConnection conn, int?commandTimeout = null) where T : BaseDBModel, new() { T obj = new T(); var sql = $"SELECT * FROM {obj.GetDBModel_SqlProvider().GetProviderOption().OpenQuote}{DBTool.GetTableName(obj)}{obj.GetDBModel_SqlProvider().GetProviderOption().CloseQuote} "; try { var lst = conn.Query <T>(sql: sql, param: obj, commandTimeout: commandTimeout, transaction: DBTool.GetTransaction(conn)).AsList(); lst.ForEach(m => { m.GetDBModel_ChangeList().Clear(); m.BeginChange(); }); return(lst); } catch (Exception e) { DBTool.DbError(e, sql.ToString() + JsonHelper.ToJSON(obj) + ExceptionTool.ToString(e)); throw; } }