using Easy4net.Common; using Easy4net.DBUtility; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Reflection; using Easy4net.CustomAttributes; using System.Text; using System.Data.Common; using System.Text.RegularExpressions; namespace Easy4net.Context { /// /// 持久层实体类 /// public class Session { /// /// 数据库连接字符串 /// private string connectionString = string.Empty; /// /// 数据库事物对象 /// private IDbTransaction m_Transaction = null; /// /// 数据库类型 /// private DatabaseType dataBaseType = DatabaseType.SQLSERVER; /// /// 数据库工厂对象,生成相应的数据库操作对象 /// private DbFactory dbFactory; /// /// /数据库工厂对象,生成相应的数据库操作对象 /// public DbFactory DbFactory { get { return dbFactory; } set { value = dbFactory; } } private Session() { } /// /// 根据数据库类型名创建一个持久层对象 /// /// /// public static Session NewInstance(ConnectionConfig config) { Session session = new Session(); session.ConnectDB(config); return session; } /// /// 获取当前的持久层对象 /// /// public static Session GetCurrentSession() { Session session = SessionThreadLocal.Get(); return session; } /// /// 根据连接类型名进行连接配置 /// /// public void ConnectDB(ConnectionConfig config) { connectionString = config.ConnectionString; dataBaseType = config.DatabaseType; dbFactory = DbFactory.NewInstance(connectionString, dataBaseType); } /// /// 开启事物处理功能 /// public void BeginTransaction() { m_Transaction = dbFactory.CreateDbTransaction(); } /// /// 根据事物锁定行为开启事物 /// /// public void BeginTransaction(System.Data.IsolationLevel level) { m_Transaction = dbFactory.CreateDbTransaction(level); } /// /// 提交事物 /// public void Commit() { if (m_Transaction != null && m_Transaction.Connection != null) { if (m_Transaction.Connection.State != ConnectionState.Closed) { m_Transaction.Commit(); m_Transaction = null; } } } /// /// 事物回滚 /// public void Rollback() { if (m_Transaction != null && m_Transaction.Connection != null) { if (m_Transaction.Connection.State != ConnectionState.Closed) { m_Transaction.Rollback(); m_Transaction = null; } } } /// /// 获取当前的事物 /// /// private IDbTransaction GetTransaction() { return m_Transaction; } #region 将实体数据保存到数据库 /// /// Insert插入操作 /// /// /// 数据库表实体对象 /// public int Insert(Object entity) { if (entity == null) return 0; object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); Type classType = entity.GetType(); //从实体对象的属性配置上获取对应的表信息 PropertyInfo[] properties = ReflectionHelper.GetProperties(classType); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.INSERT, properties); //获取SQL语句 String strSql = EntityHelper.GetInsertSql(tableInfo); //获取参数 IDbDataParameter[] parms = tableInfo.GetParameters(); //执行Insert命令 val = AdoHelper.ExecuteScalar(dbFactory, connection, transaction, CommandType.Text, strSql, parms); //把自动生成的主键ID赋值给返回的对象 if (!tableInfo.NoAutomaticKey && tableInfo.Strategy == GenerationType.INDENTITY) { if (dataBaseType == DatabaseType.SQLSERVER || dataBaseType == DatabaseType.MYSQL || dataBaseType == DatabaseType.SQLITE) { PropertyInfo propertyInfo = EntityHelper.GetPrimaryKeyPropertyInfo(entity, properties); ReflectionHelper.SetPropertyValue(entity, propertyInfo, val); } } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 批量保存 /// /// 批量进行Insert插入操作 /// /// /// 数据库表实体对象集合 /// public int Insert(List entityList) { if (entityList == null || entityList.Count == 0) return 0; object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); //从实体对象的属性配置上获取对应的表信息 T firstEntity = entityList[0]; Type classType = firstEntity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(classType); TableInfo tableInfo = EntityHelper.GetTableInfo(firstEntity, DbOperateType.INSERT, properties); //获取SQL语句 String strSQL = EntityHelper.GetInsertSql(tableInfo); foreach (T entity in entityList) { //从实体对象的属性配置上获取对应的表信息 tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.INSERT, properties); //获取参数 IDbDataParameter[] parms = tableInfo.GetParameters(); //执行Insert命令 val = AdoHelper.ExecuteScalar(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); //Access数据库执行不需要命名参数 if (dataBaseType == DatabaseType.ACCESS) { //如果是Access数据库,另外执行获取自动生成的ID String autoSql = EntityHelper.GetAutoSql(dbFactory.DbType); val = AdoHelper.ExecuteScalar(dbFactory, connection, transaction, CommandType.Text, autoSql); } //把自动生成的主键ID赋值给返回的对象 if (!tableInfo.NoAutomaticKey && tableInfo.Strategy == GenerationType.INDENTITY) { //把自动生成的主键ID赋值给返回的对象 if (dataBaseType == DatabaseType.SQLSERVER || dataBaseType == DatabaseType.MYSQL || dataBaseType == DatabaseType.ACCESS || dataBaseType == DatabaseType.SQLITE) { PropertyInfo propertyInfo = EntityHelper.GetPrimaryKeyPropertyInfo(entity, properties); ReflectionHelper.SetPropertyValue(entity, propertyInfo, val); } } } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 将实体数据修改到数据库 /// /// Update更新操作 /// /// /// 数据库表实体对象 /// public int Update(Object entity) { if (entity == null) return 0; object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); Type classType = entity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(classType); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.UPDATE, properties); String strSQL = EntityHelper.GetUpdateSql(tableInfo); List paramsList = tableInfo.GetParameterList(); IDbDataParameter dbParameter = dbFactory.CreateDbParameter(tableInfo.Id.Key, tableInfo.Id.Value); paramsList.Add(dbParameter); IDbDataParameter[] parms = tableInfo.GetParameters(paramsList); val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 批量更新 /// /// 批量进行Update更新操作 /// /// /// 数据库表实体对象集合 /// public int Update(List entityList) { if (entityList == null || entityList.Count == 0) return 0; object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); T firstEntity = entityList[0]; Type classType = firstEntity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(firstEntity.GetType()); TableInfo tableInfo = EntityHelper.GetTableInfo(firstEntity, DbOperateType.UPDATE, properties); String strSQL = EntityHelper.GetUpdateSql(tableInfo); /*tableInfo.Columns.Add(tableInfo.Id.Key, tableInfo.Id.Value); IDbDataParameter[] parms = tableInfo.GetParameters();*/ foreach (T entity in entityList) { tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.UPDATE, properties); List paramsList = tableInfo.GetParameterList(); IDbDataParameter dbParameter = dbFactory.CreateDbParameter(tableInfo.Id.Key, tableInfo.Id.Value); paramsList.Add(dbParameter); IDbDataParameter[] parms = tableInfo.GetParameters(paramsList); val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 执行SQL语句 /// /// 执行一条带有参数集合的SQL语句 /// /// SQL语句 /// 参数集合 /// public int ExcuteSQL(string strSQL, ParamMap param) { object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); IDbDataParameter[] parms = param.toDbParameters(); if (dataBaseType == DatabaseType.ACCESS) { strSQL = SQLBuilderHelper.builderAccessSQL(strSQL, parms); val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL); } else { val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 执行SQL语句 /// /// 执行一条SQL语句 /// /// /// public int ExcuteSQL(string strSQL) { object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL); } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 删除实体对应数据库中的数据 /// /// 进行Delete删除操作 /// /// /// 数据库表实体对象 /// public int Delete(T entity) { if (entity == null) return 0; object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); Type classType = entity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(classType); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.DELETE, properties); IDbDataParameter[] parms = dbFactory.CreateDbParameters(1); parms[0].ParameterName = tableInfo.Id.Key; parms[0].Value = tableInfo.Id.Value; String strSQL = EntityHelper.GetDeleteByIdSql(tableInfo); if (dataBaseType == DatabaseType.ACCESS) { strSQL = SQLBuilderHelper.builderAccessSQL(classType, tableInfo, strSQL, parms); val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL); } else { val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 批量删除 /// /// 批量进行Delete删除操作 /// /// /// 数据库表实体对象集合 /// public int Delete(List entityList) { if (entityList == null || entityList.Count == 0) return 0; object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); T firstEntity = entityList[0]; Type classType = firstEntity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(firstEntity.GetType()); TableInfo tableInfo = EntityHelper.GetTableInfo(firstEntity, DbOperateType.DELETE, properties); String strSQL = EntityHelper.GetDeleteByIdSql(tableInfo); foreach (T entity in entityList) { tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.DELETE, properties); IDbDataParameter[] parms = dbFactory.CreateDbParameters(1); parms[0].ParameterName = tableInfo.Id.Key; parms[0].Value = tableInfo.Id.Value; if (dataBaseType == DatabaseType.ACCESS) { strSQL = SQLBuilderHelper.builderAccessSQL(classType, tableInfo, strSQL, parms); val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL); } else { val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); } //val = AdoHelper.ExecuteNonQuery(connection, transaction, CommandType.Text, strSQL, parms); } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 根据主键id删除实体对应数据库中的数据 /// /// 根据主键值删除实体类对应数据库中的数据 /// /// /// 主键值 /// public int Delete(object id) where T : new() { object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); T entity = new T(); Type classType = entity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(entity.GetType()); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.DELETE, properties); String strSQL = EntityHelper.GetDeleteByIdSql(tableInfo); IDbDataParameter[] parms = dbFactory.CreateDbParameters(1); parms[0].ParameterName = tableInfo.Id.Key; parms[0].Value = id; if (dataBaseType == DatabaseType.ACCESS) { strSQL = SQLBuilderHelper.builderAccessSQL(classType, tableInfo, strSQL, parms); val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL); } else { val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 批量根据主键id删除数据 /// /// 根据主键ID集合进行删除操作 /// /// /// /// public int Delete(object[] ids) where T : new() { if (ids == null || ids.Length == 0) return 0; object val = 0; IDbTransaction transaction = null; IDbConnection connection = null; try { //获取数据库连接,如果开启了事务,从事务中获取 connection = GetConnection(); transaction = GetTransaction(); T entity = new T(); Type classType = entity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(entity.GetType()); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.DELETE, properties); String strSQL = EntityHelper.GetDeleteByIdSql(tableInfo); foreach (object id in ids) { tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.DELETE, properties); IDbDataParameter[] parms = dbFactory.CreateDbParameters(1); parms[0].ParameterName = tableInfo.Id.Key; parms[0].Value = id; val = AdoHelper.ExecuteNonQuery(dbFactory, connection, transaction, CommandType.Text, strSQL, parms); } } catch (Exception e) { throw e; } finally { if (m_Transaction == null) { connection.Close(); } } return Convert.ToInt32(val); } #endregion #region 通过自定义SQL语句查询记录数 /// /// 根据SQL语句获取记录数 /// /// /// public int Count(string strSQL) { int count = 0; IDbConnection connection = null; bool closeConnection = GetWillConnectionState(); try { connection = GetConnection(); count = Convert.ToInt32(AdoHelper.ExecuteScalar(dbFactory, connection, CommandType.Text, strSQL)); } catch (Exception ex) { throw ex; } finally { if (closeConnection) { connection.Close(); } } return count; } #endregion #region 通过自定义SQL语句查询记录数 /// /// 通过自定义SQL语句查询记录数 /// /// /// 参数集合 /// public int Count(string strSql, ParamMap param) { int count = 0; IDbConnection connection = null; bool closeConnection = GetWillConnectionState(); try { connection = GetConnection(); strSql = strSql.ToLower(); String columns = SQLBuilderHelper.fetchColumns(strSql); if (dataBaseType == DatabaseType.ACCESS) { strSql = SQLBuilderHelper.builderAccessSQL(strSql, param.toDbParameters()); count = Convert.ToInt32(AdoHelper.ExecuteScalar(dbFactory, connection, CommandType.Text, strSql)); } else { count = Convert.ToInt32(AdoHelper.ExecuteScalar(dbFactory, connection, CommandType.Text, strSql, param.toDbParameters())); } } catch (Exception ex) { throw ex; } finally { if (closeConnection) { connection.Close(); } } return count; } #endregion #region 通过自定义SQL语句查询数据 /// /// 通过自定义SQL语句查询数据 /// /// /// /// public List Find(string strSql) where T : new() { List list = new List(); IDataReader sdr = null; IDbConnection connection = null; try { connection = GetConnection(); bool closeConnection = GetWillConnectionState(); strSql = strSql.ToLower(); String columns = SQLBuilderHelper.fetchColumns(strSql); T entity = new T(); PropertyInfo[] properties = ReflectionHelper.GetProperties(entity.GetType()); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.SELECT, properties); sdr = AdoHelper.ExecuteReader(dbFactory, closeConnection, connection, CommandType.Text, strSql, null); list = EntityHelper.toList(sdr, tableInfo, properties); } catch (Exception ex) { throw ex; } finally { if (sdr != null) sdr.Close(); } return list; } #endregion #region 通过自定义SQL语句查询数据 /// /// 通过自定义SQL语句查询数据 /// /// /// /// /// public List Find(string strSQL, ParamMap param) where T : new() { List list = new List(); IDataReader sdr = null; IDbConnection connection = null; try { connection = GetConnection(); bool closeConnection = GetWillConnectionState(); string lowerSQL = strSQL.ToLower(); String columns = SQLBuilderHelper.fetchColumns(lowerSQL); T entity = new T(); Type classType = entity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(classType); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.SELECT, properties); if (param.IsPage && !SQLBuilderHelper.isPage(lowerSQL)) { strSQL = SQLBuilderHelper.builderPageSQL(strSQL, param.OrderFields, param.IsDesc); } if (dataBaseType == DatabaseType.ACCESS) { strSQL = SQLBuilderHelper.builderAccessPageSQL(strSQL, param); } sdr = AdoHelper.ExecuteReader(dbFactory, closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters()); list = EntityHelper.toList(sdr, tableInfo, properties); } catch (Exception ex) { throw ex; } finally { if (sdr != null) sdr.Close(); } return list; } public DataRow FindRow(string strSQL, ParamMap param) { var table = FindTable(strSQL,param); if (table != null && table.Rows.Count > 0) return table.Rows[0]; else return null; } public DataTable FindTable(string strSQL, ParamMap param) { IDataReader sdr = null; IDbConnection connection = null; try { connection = GetConnection(); bool closeConnection = GetWillConnectionState(); string lowerSQL = strSQL.ToLower(); String columns = SQLBuilderHelper.fetchColumns(lowerSQL); if (param.IsPage && !SQLBuilderHelper.isPage(lowerSQL)) { strSQL = SQLBuilderHelper.builderPageSQL(strSQL, param.OrderFields, param.IsDesc); } if (dataBaseType == DatabaseType.ACCESS) { strSQL = SQLBuilderHelper.builderAccessPageSQL(strSQL, param); } sdr = AdoHelper.ExecuteReader(dbFactory, closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters()); return GetDataTableFromIDataReader(sdr); } catch (Exception ex) { throw ex; } finally { if (sdr != null) sdr.Close(); } } public List Find(string strSQL, Object obj) where T : new() { if (dataBaseType == DatabaseType.MYSQL) { strSQL = strSQL.Replace("[随机排序]", " order by rand() "); } else { strSQL = strSQL.Replace("[随机排序]", " order by RANDOM() "); } //获取公共属性 PropertyInfo[] propertys = obj.GetType().GetProperties(); ParamMap map = ParamMap.NewMap(); foreach (System.Reflection.PropertyInfo p in propertys) { map.Add(p.Name,p.GetValue(obj)); } return Find(strSQL,map); } public DataRow FindRow(string strSQL, Object obj) { if (dataBaseType == DatabaseType.MYSQL) { strSQL = strSQL.Replace("[随机排序]", " order by rand() "); } else { strSQL = strSQL.Replace("[随机排序]", " order by RANDOM() "); } //获取公共属性 PropertyInfo[] propertys = obj.GetType().GetProperties(); ParamMap map = ParamMap.NewMap(); foreach (System.Reflection.PropertyInfo p in propertys) { map.Add(p.Name, p.GetValue(obj)); } return FindRow(strSQL, map); } public DataTable FindTable(string strSQL, Object obj) { if (dataBaseType == DatabaseType.MYSQL) { strSQL = strSQL.Replace("[随机排序]", " order by rand() "); } else { strSQL = strSQL.Replace("[随机排序]", " order by RANDOM() "); } //获取公共属性 PropertyInfo[] propertys = obj.GetType().GetProperties(); ParamMap map = ParamMap.NewMap(); foreach (System.Reflection.PropertyInfo p in propertys) { map.Add(p.Name, p.GetValue(obj)); } return FindTable(strSQL, map); } private DataTable GetDataTableFromIDataReader(IDataReader reader) { DataTable dt = new DataTable(); bool init = false; dt.BeginLoadData(); object[] vals = new object[0]; while (reader.Read()) { if (!init) { init = true; int fieldCount = reader.FieldCount; for (int i = 0; i < fieldCount; i++) { dt.Columns.Add(reader.GetName(i), reader.GetFieldType(i)); } vals = new object[fieldCount]; } reader.GetValues(vals); dt.LoadDataRow(vals, true); } reader.Close(); dt.EndLoadData(); return dt; } #endregion #region 分页查询返回分页结果 /// /// 分页查询返回分页结果 /// /// /// /// /// public PageResult FindPage(string strSQL, ParamMap param) where T : new() { PageResult pageResult = new PageResult(); List list = new List(); IDataReader sdr = null; IDbConnection connection = null; try { connection = GetConnection(); bool closeConnection = GetWillConnectionState(); strSQL = strSQL.ToLower(); String countSQL = SQLBuilderHelper.builderCountSQL(strSQL); String columns = SQLBuilderHelper.fetchColumns(strSQL); int count = this.Count(countSQL, param); T entity = new T(); Type classType = entity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(classType); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.SELECT, properties); if (param.IsPage && !SQLBuilderHelper.isPage(strSQL)) { strSQL = SQLBuilderHelper.builderPageSQL(strSQL, param.OrderFields, param.IsDesc); } if (dataBaseType == DatabaseType.ACCESS) { if (param.getInt("page_offset") > count) { int limit = param.getInt("page_limit") + count - param.getInt("page_offset"); if (limit > 0) { strSQL = SQLBuilderHelper.builderAccessPageSQL(strSQL, param, limit); sdr = AdoHelper.ExecuteReader(dbFactory, closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters()); list = EntityHelper.toList(sdr, tableInfo, properties); } } else { strSQL = SQLBuilderHelper.builderAccessPageSQL(strSQL, param); sdr = AdoHelper.ExecuteReader(dbFactory, closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters()); list = EntityHelper.toList(sdr, tableInfo, properties); } } else { sdr = AdoHelper.ExecuteReader(dbFactory, closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters()); list = EntityHelper.toList(sdr, tableInfo, properties); } pageResult.Total = count; pageResult.DataList = list; } catch (Exception ex) { throw ex; } finally { if (sdr != null) sdr.Close(); } return pageResult; } #endregion #region 通过主键ID查询数据 /// /// 通过主键ID查询数据 /// /// /// /// public T Get(object id) where T : new() { List list = new List(); IDataReader sdr = null; IDbConnection connection = null; try { connection = GetConnection(); bool closeConnection = GetWillConnectionState(); T entity = new T(); Type classType = entity.GetType(); PropertyInfo[] properties = ReflectionHelper.GetProperties(classType); TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.SELECT, properties); IDbDataParameter[] parms = dbFactory.CreateDbParameters(1); parms[0].ParameterName = tableInfo.Id.Key; parms[0].Value = id; String strSQL = EntityHelper.GetFindByIdSql(tableInfo); sdr = AdoHelper.ExecuteReader(dbFactory, closeConnection, connection, CommandType.Text, strSQL, parms); list = EntityHelper.toList(sdr, tableInfo, properties); } catch (Exception ex) { throw ex; } finally { if (sdr != null) sdr.Close(); } return list.FirstOrDefault(); } #endregion /// /// 获取数据库连接 /// /// private IDbConnection GetConnection() { //获取数据库连接,如果开启了事务,从事务中获取 IDbConnection connection = null; if (m_Transaction != null) { connection = m_Transaction.Connection; } else { connection = dbFactory.CreateDbConnection(); } return connection; } /// /// 获取当前事物是否为空 /// /// private bool GetWillConnectionState() { return m_Transaction == null; } /// /// 创建表 /// /// public void CreateTable() { CreateTable(typeof(T)); } /// /// 创建表 /// /// public void CreateTable(Type type) { //获取公共属性 PropertyInfo[] Propertys = type.GetProperties(); if (Propertys.Length == 1) throw new Exception("字段最少需要2个。"); StringBuilder sb = new StringBuilder(); sb.Append("CREATE TABLE "); sb.Append(type.Name); sb.Append("("); int number = 0; foreach (var item in Propertys) { string _name = item.Name; string _type = string.Empty; bool _primary = false; var _unique = " "; var _attribute = item.GetCustomAttributes().FirstOrDefault(f=>f.GetType()== typeof(ColumnAttribute)) as ColumnAttribute; if (_attribute != null) { _name = _attribute.Name; _type = _attribute.TypeInfo; _primary = _attribute.PrimaryKey; _unique = _attribute.IsUnique? " unique " : " "; } if (string.IsNullOrEmpty(_name)) _name = item.Name; number++; sb.Append(_name); if (item.Name.ToLower() == "id" || _primary) { sb.Append(" integer primary key 自增 not null "); } else if (!string.IsNullOrEmpty(_type)) { sb.Append(" "+_type+ _unique); } else { sb.Append(" "); if (item.PropertyType.FullName == typeof(Int32).ToString() || item.PropertyType.FullName == typeof(Int16).ToString() || item.PropertyType.FullName == typeof(UInt16).ToString() || item.PropertyType.FullName == typeof(Int64).ToString()) sb.Append(" integer default 0 " + _unique); else if (typeof(DateTime).ToString() == item.PropertyType.FullName) sb.Append(" datetime " + _unique); else if (typeof(String).ToString() == item.PropertyType.FullName) { if (_name.ToUpper() == "message".ToUpper() || _name.ToUpper() == "answer".ToUpper() || _name.ToUpper() == "token".ToUpper()) { sb.Append(" text " + _unique); } else sb.Append(" varchar(255) default ''" + _unique); } else if (item.PropertyType.FullName == typeof(Char).ToString()) sb.Append(" varchar(2) default ''" + _unique); else if (item.PropertyType.FullName == typeof(Boolean).ToString()) sb.Append(" boolean " + _unique); else if (item.PropertyType.FullName == typeof(Double).ToString()) sb.Append(" double default 0.00" + _unique); else { throw new Exception("不支持" + item.PropertyType.FullName + "字段,请联系框架设计师处理。"); } } if (number != Propertys.Length) { sb.Append(","); } } sb.Append(");"); string sql = sb.ToString(); if (sql.Contains("自增")) { if (dataBaseType == DatabaseType.SQLITE) { sql = sql.Replace("自增", "AUTOINCREMENT").Replace("AUTO_INCREMENT", "AUTOINCREMENT"); } else if(dataBaseType == DatabaseType.MYSQL) { sql = sql.Replace("自增", "AUTO_INCREMENT").Replace("AUTOINCREMENT", "AUTO_INCREMENT"); } } ExcuteSQL(sql); } /// /// 添加唯一约束 /// public void AddUnique(params object[] values) { AddUnique(typeof(T).Name, values); } /// /// 添加唯一约束 /// public void AddUnique(string tableName, params object[] values) { if (values == null) throw new Exception("Unique 不能为空。"); StringBuilder sb = new StringBuilder(); if (dataBaseType == DatabaseType.SQLITE) { sb.Append(" CREATE UNIQUE INDEX "); sb.Append(tableName); foreach (var item in values) { sb.Append("_"); sb.Append(item); sb.Append("_"); } sb.Append(" ON "); sb.Append(tableName); sb.Append("("); for (int i = 0; i < values.Length; i++) { sb.Append(values[i]); if ((i + 1) != values.Length) { sb.Append(","); } } sb.Append(");"); } else if (dataBaseType == DatabaseType.MYSQL) { sb.Append("ALTER TABLE "); sb.Append(tableName); sb.Append(" ADD UNIQUE KEY("); for (int i = 0; i < values.Length; i++) { sb.Append(values[i]); if ((i + 1) != values.Length) { sb.Append(","); } } sb.Append(");"); } else throw new Exception("暂时不支持"+dataBaseType+"数据库!"); ExcuteSQL(sb.ToString()); } /// /// 添加索引 /// public bool AddIndex(string indexName, params object[] values) { try { string tableName = typeof(T).Name; StringBuilder sb = new StringBuilder(); if (dataBaseType == DatabaseType.SQLITE) { sb.Append(" CREATE INDEX "); sb.Append(indexName); foreach (var item in values) { sb.Append("_"); sb.Append(item); sb.Append("_"); } sb.Append(" ON "); sb.Append(tableName); sb.Append("("); for (int i = 0; i < values.Length; i++) { sb.Append(values[i]); if ((i + 1) != values.Length) { sb.Append(","); } } sb.Append(");"); } else if (dataBaseType == DatabaseType.MYSQL) { sb.Append("ALTER TABLE "); sb.Append(tableName); sb.Append(" ADD INDEX " + indexName + "("); for (int i = 0; i < values.Length; i++) { sb.Append(values[i]); if ((i + 1) != values.Length) { sb.Append(","); } } sb.Append(");"); } else throw new Exception("暂时不支持" + dataBaseType + "数据库!"); ExcuteSQL(sb.ToString()); return true; } catch (Exception ex) { Console.WriteLine("创建索引失败:" + ex.Message); } return false; } /// /// 判断表是否存在 /// /// /// public bool TableExist() { return TableExist(typeof(T).Name); } /// /// 判断表是否存在 /// public bool TableExist(string tableName) { ParamMap param = ParamMap.NewMap(); param.setParameter("tableName", tableName); if (dataBaseType== DatabaseType.SQLITE) { var result =FindRow("SELECT * FROM sqlite_master where type='table' and name=@tableName;", param); if (result == null) return false; } else if (dataBaseType == DatabaseType.MYSQL) { param.setParameter("dbName", Regex.Match(connectionString,"Initial Catalog=(.*?);").Groups[1].Value); var result = FindRow("select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA=@dbName and TABLE_NAME=@tableName ;",param); if (result == null) return false; } else return false; return true; } } }