C# · 12月 19, 2021

OracleHelper(对增删改查分页查询操作进行了面向对象的封装,对批量增删改操作的事务封装)

    公司的一个新项目使用ASP.NET MVC开发,经理让我写个OracleHelper,我从网上找了一个比较全的OracleHelper类,缺点是查询的时候返回DataSet,数据增删改要写很多代码(当然,可以用代码生成器,不过配套的代码生成器暂时没有);又从网上找了一个封装了泛型方法的OracleHelper类,整合到一起,但貌似数据增删改查依然不方便;于是花了两天时间,在原有基础上对增删改查分页查询操作进行了面向对象的封装,并且对批量增删改操作进行事务封装,写事务代码更方便。

 

原理:

1、利用反射对增删改查进行面向对象的封装

2、事务:如果没有开启事务(没有调用OracleHelper类的BeginTransaction方法),则按原来的方法创建连接,操作数据库,然后关闭连接;如果开启了事务(调用了OracleHelper类的BeginTransaction方法),则一次Http请求使用同一个OracleConnection,增删改操作后不关闭连接,先提交事务,事务提交后才关闭连接,下次Http请求再重新创建一个OracleConnection。

 

说明:

OracleHelper类包含如下功能:

1、基础方法(执行简单sql语句;执行带参数的sql语句;存储过程操作;)

2、扩展方法(泛型方法)

3、增删改查(封装了增删改查分页查询操作;查询主表数据时,关联表数据作为主表的类的属性直接查询出来,而不只是关联表数据的ID;添加操作,关联表数据和主表数据要分别添加(使用事务确保一致性);删除操作,关联表数据和主表数据要分别删除(使用事务确保一致性);修改操作,如果关联表的是新增的(即ID变了),要先添加关联表数据,再更新主表数据,如果关联表不是新增的(即ID没变),则只需要更新主表,方法中会自动更新关联表(关联表如果还有关联表也支持))

4、事务

 

代码:

OracleHelper.cs:

using System; System.Collections; System.Collections.Generic; System.Configuration; System.Data; System.Data.OracleClient; System.Linq; System.Reflection; System.Text; System.Xml.Linq; Models; System.Web;namespace DBUtil{ /// <summary> /// Oracle操作类 2014年9月25日 写程序之前,首先引用System.Data.OracleClient </summary> public class OracleHelper { #region 变量 <summary> 数据库连接字符串 </summary> static string connectionString = ConfigurationManager.ConnectionStrings[“DefaultConnection”].ToString(); #endregion #region 事务的OracleConnection #region 数据库连接对象 获取打开的数据库连接对象 static OracleConnection GetOpenConnection() { OracleConnection connection = null; string key = Simpo_FQD_OracleConnectionif (HttpContext.Current.Items[key] == ) { connection = new OracleConnection(connectionString); connection.open(); HttpContext.Current.Items[key] = connection; } else { connection = (OracleConnection)HttpContext.Current.Items[key]; } return connection; } #region 事务对象 获取事务对象 OracleTransaction GetTran() { OracleTransaction tran = Simpo_FQD_OracleTransaction) { tran = GetOpenConnection().BeginTransaction(); HttpContext.Current.Items[key] = tran; } { tran = (OracleTransaction)HttpContext.Current.Items[key]; } tran; } #region 开起事务标志 事务标志 private string tranFlagKey = Simpo_FQD_OracleTransaction_Flag; 添加事务标志 void AddTranFlag() { HttpContext.Current.Items[tranFlagKey] = true; } 移除事务标志 RemoveTranFlag() { HttpContext.Current.Items[tranFlagKey] = falsebool TranFlag { get { bool tranFlag = ; if (HttpContext.Current.Items[tranFlagKey] != ) { tranFlag = ()HttpContext.Current.Items[tranFlagKey]; } tranFlag; } } #endregion #region 基础方法 #region 公用方法 #region GetMaxID 不支持多用户并发,慎用,请使用GetNextID方法 int GetMaxID(string fieldName,string tableName) { string strsql = select max(” + fieldName + )+1 from ” + tableName; object obj = OracleHelper.GetSingle(strsql); if (obj == ) { return 1; } return int.Parse(obj.ToString()); } } #region Exists bool Exists(string strsql,1)”>params OracleParameter[] cmdParms) { OracleHelper.GetSingle(strsql,cmdParms); cmdresult; if ((Object.Equals(obj,1)”>null)) || (Object.Equals(obj,System.DBNull.Value))) { cmdresult = 0 { cmdresult = .Parse(obj.ToString()); } if (cmdresult == ; } } #region 执行简单sql语句 sqlString) { using (OracleConnection connection = OracleConnection(connectionString)) { using (OracleCommand cmd = OracleCommand(sqlString,connection)) { try { connection.open(); cmd.ExecuteScalar(); ; } { ; } } catch (System.Data.OracleClient.OracleException e) { connection.Close(); throw Exception(e.Message); } finally { cmd.Dispose(); connection.Close(); } } } } #region 执行sql语句,返回影响的记录数 执行sql语句,返回影响的记录数 </summary> <param name=”sqlString”>sql语句</param> <returns>影响的记录数</returns> int Executesql( sqlString) { OracleConnection connection = GetOpenConnection(); { if (TranFlag) cmd.Transaction = GetTran(); int rows = cmd.ExecuteNonQuery(); rows; } (System.Data.OracleClient.OracleException E) { connection.Close(); Exception(E.Message); } { cmd.Dispose(); if (!TranFlag) connection.Close(); } } } #region 执行多条sql语句,实现数据库事务 执行多条sql语句,实现数据库事务。 <param name=”sqlStringList”>多条sql语句</param> ExecutesqlTran(ArrayList sqlStringList) { bool re = ; OracleConnection(connectionString)) { connection.open(); OracleCommand cmd = OracleCommand(); cmd.Connection = connection; OracleTransaction tx = connection.BeginTransaction(); cmd.Transaction = tx; for (int n = 0; n < sqlStringList.Count; n++) { string strsql = sqlStringList[n].ToString(); if (strsql.Trim().Length > ) { cmd.CommandText = strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); re = ; } (System.Data.OracleClient.OracleException E) { re = ; tx.Rollback(); { cmd.Dispose(); connection.Close(); } } re; } #region 执行带一个存储过程参数的的sql语句 执行带一个存储过程参数的的sql语句。 <param name=”content”>参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加string sqlString,1)”> content) { OracleConnection(connectionString)) { OracleCommand cmd = = new System.Data.OracleClient.OracleParameter(@content,OracleType.NVarChar); myParameter.Value = content; cmd.Parameters.Add(myParameter); { connection.open(); (System.Data.OracleClient.OracleException E) { { cmd.Dispose(); connection.Close(); } } } #region 向数据库里插入图像格式的字段 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) <param name=”strsql”><param name=”fs”>图像字节,数据库的字段类型为image的情况int ExecutesqlInsertImg(string strsql,1)”>byte[] fs) { OracleCommand(strsql,1)”>@fs= fs; cmd.Parameters.Add(myParameter); #region 执行一条计算查询结果语句,返回查询结果 执行一条计算查询结果语句,返回查询结果(object)。 计算查询结果语句查询结果(object)object GetSingle( obj; } } #region 执行查询语句,返回OracleDataReader 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对sqlDataReader进行Close ) 查询语句OracleDataReaderstatic OracleDataReader ExecuteReader( strsql) { OracleConnection connection = OracleConnection(connectionString); OracleCommand cmd = { connection.open(); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); myReader; } (System.Data.OracleClient.OracleException e) { Exception(e.Message); } } #region 执行查询语句,返回DataSet 执行查询语句,返回DataSet DataSetstatic DataSet Query( OracleConnection(connectionString)) { DataSet ds = DataSet(); { connection.open(); OracleDataAdapter command = OracleDataAdapter(sqlString,connection); command.Fill(ds,ds); } (System.Data.OracleClient.OracleException ex) { Exception(ex.Message); } { connection.Close(); } ds; } } #region 执行带参数的sql语句 OracleParameter[] cmdParms) { OracleConnection connection = OracleCommand()) { { PrepareCommand(cmd,connection, cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); sql语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param> ExecutesqlTran(Hashtable sqlStringList) { using (OracleConnection conn = OracleConnection(connectionString)) { conn.open(); using (OracleTransaction trans = conn.BeginTransaction()) { OracleCommand cmd = OracleCommand(); { //循环 foreach (DictionaryEntry myDE in sqlStringList) { string cmdText = myDE.Key.ToString(); OracleParameter[] cmdParms = (OracleParameter[])myDE.Value; PrepareCommand(cmd,conn,trans,cmdText,cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); trans.Commit(); } } { trans.Rollback(); throw; } } } } OracleCommand()) { { PrepareCommand(cmd,cmdParms); cmd.ExecuteScalar(); cmd.Parameters.Clear(); (System.Data.OracleClient.OracleException e) { OracleParameter[] cmdParms) { OracleConnection connection = OracleCommand(); { PrepareCommand(cmd,cmdParms); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); Exception(e.Message); } } OracleCommand(); PrepareCommand(cmd,cmdParms); using (OracleDataAdapter da = OracleDataAdapter(cmd)) { DataSet ds = DataSet(); { da.Fill(ds,1)”>); cmd.Parameters.Clear(); } (System.Data.OracleClient.OracleException ex) { Exception(ex.Message); } { cmd.Dispose(); connection.Close(); } ds; } } } #region PrepareCommand void PrepareCommand(OracleCommand cmd,OracleConnection conn,OracleTransaction trans,1)”> cmdText,OracleParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != ) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;cmdType; if (cmdParms != foreach (OracleParameter parm cmdParms) cmd.Parameters.Add(parm); } } #region 存储过程操作 #region 执行存储过程 返回sqlDataReader 执行存储过程 返回sqlDataReader ( 注意:调用该方法后,一定要对sqlDataReader进行Close ) <param name=”storedProcName”>存储过程名<param name=”parameters”>存储过程参数static OracleDataReader RunProcedureReader( storedProcName,IDataParameter[] parameters) { OracleConnection connection = OracleConnection(connectionString); OracleDataReader returnReader; connection.open(); OracleCommand command = BuildQueryCommand(connection,storedProcName,parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); returnReader; } #region 执行存储过程,返回影响的行数 执行存储过程,返回影响的行数 <param name=”rowsAffected”>影响的行数<returns></returns> int RunProcedure(string storedProcName,IDataParameter[] parameters,1)”>out rowsAffected) { result; connection.open(); OracleCommand command = BuildIntCommand(connection,parameters); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters[ReturnValue].Value; Connection.Close(); result; } } #region 执行存储过程,什么值也不返回 执行存储过程,什么值也不返回 <param name=”storedProcName”></param> <param name=”parameters”></param> void RunProcedure( OracleConnection(connectionString)) { System.Data.OracleClient.OracleCommand cmd =if (connection.State != ConnectionState.Open) { connection.open(); } cmd.ExecuteNonQuery(); } (Exception ex) { ex.Message.ToString(); Exception(ex.Message); Console.WriteLine(ex.Message.ToString()); } { connection.Close(); } } } #region 执行存储过程,返回数据集 执行存储过程,返回数据集 <param name=”tableName”>DataSet结果中的表名static DataSet RunProcedureGetDataSet( OracleConnection(connectionString)) { DataSet dataSet = DataSet(); connection.open(); OracleDataAdapter sqlDA = OracleDataAdapter(); sqlDA.SelectCommand =dt); connection.Close(); dataSet; } } #region 构建 OracleCommand 对象 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值) <param name=”connection”>数据库连接OracleCommandstatic OracleCommand BuildQueryCommand(OracleConnection connection,IDataParameter[] parameters) { OracleCommand command = OracleCommand(storedProcName,connection); command.CommandType = CommandType.StoredProcedure; foreach (OracleParameter parameter parameters) { command.Parameters.Add(parameter); } command; } int RunProcedure_rowsAffected(#region 创建 OracleCommand 对象实例 创建 OracleCommand 对象实例(用来返回一个整数值) OracleCommand 对象实例static OracleCommand BuildIntCommand(OracleConnection connection,IDataParameter[] parameters) { OracleCommand command =new OracleParameter(4false,0,1)”>string.Empty,DaTarowVersion.Default,1)”>)); #region 扩展方法 #region 执行返回一行一列的数据库操作 执行返回一行一列的数据库操作 <param name=”commandText”>Oracle语句或存储过程名<param name=”commandType”>Oracle命令类型<param name=”param”>Oracle命令参数数组第一行第一列的记录int ExecuteScalar(string commandText,CommandType commandType,1)”> OracleParameter[] param) { int count = OracleCommand(commandText,1)”> { cmd.CommandType = commandType; cmd.Parameters.AddRange(param); connection.open(); count = Convert.ToInt32(cmd.ExecuteScalar()); } (Exception ex) { count = ; } } } count; } #region 执行不查询的数据库操作 执行不查询的数据库操作 受影响的行数int ExecuteNonQuery(int result = commandType; cmd.Parameters.AddRange(param); connection.open(); result = cmd.ExecuteNonQuery(); } (Exception ex) { result = result; } #region 执行返回一条记录的泛型对象 执行返回一条记录的泛型对象 <typeparam name=”T”>泛型类型</typeparam> <param name=”reader”>只进只读对象泛型对象static T ExecuteDataReader<T>(IDataReader reader) { T obj = default(T); { Type type = typeof(T); obj = (T)Activator.CreateInstance(type);从当前程序集里面通过反射的方式创建指定类型的对象 obj = (T)Assembly.Load(OracleHelper._assemblyName).CreateInstance(OracleHelper._assemblyName + “.” + type.Name);从另一个程序集里面通过反射的方式创建指定类型的对象 PropertyInfo[] propertyInfos = type.GetProperties();获取指定类型里面的所有属性 foreach (PropertyInfo propertyInfo propertyInfos) { int i = 0; i < reader.FieldCount; i++string fieldName = reader.GetName(i); if (fieldName.ToLower() == propertyInfo.Name.ToLower()) { object val = reader[propertyInfo.Name];读取表中某一条记录里面的某一列信息 if (val != null && val != DBNull.Value) propertyInfo.SetValue(obj,val,1)”>null);给对象的某一个属性赋值 break; } } } } (Exception ex) { } obj; } 实体对象static T ExecuteEntity<T>( OracleParameter[] param) { T obj = = commandType; cmd.Parameters.AddRange(param); connection.open(); OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { obj = OracleHelper.ExecuteDataReader<T>(reader); } } } #region 执行返回多条记录的泛型集合对象 执行返回多条记录的泛型集合对象 泛型集合对象static List<T> ExecuteList<T>( OracleParameter[] param) { List<T> list = new List<T>(); commandType; cmd.Parameters.AddRange(param); connection.open(); OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); (reader.Read()) { T obj = OracleHelper.ExecuteDataReader<T>(reader); list.Add(obj); } } (Exception ex) { list = list; } #region 增删改查 #region 根据sequence名称获取下一个ID 根据sequence名称获取下一个ID int GetNextID( sequenceName) { string sql = string.Format(select {0}.Nextval from dual= Query(sql).Tables[]; int.Parse(dt.Rows[0][].ToString()); } #region 添加 添加 void Insert(object obj) { StringBuilder strsql = StringBuilder(); Type type = obj.GetType(); strsql.Append(insert into {0}(= type.GetProperties(); List<string> propertyNameList = new List<string>int savedCount = propertyInfoList) { if (propertyInfo.GetCustomAttributes(typeof(NotSaveAttribute),1)”>false).Length == ) { typeof(IsEntityAttribute),1)”>object val = propertyInfo.GetValue(obj,1)”>); ) { propertyNameList.Add(propertyInfo.Name); savedCount++) { propertyNameList.Add(propertyInfo.Name + Id); savedCount++; } } } } strsql.Append({0})”,1)”>string.Join( values ({0})string>(a => : a).ToArray()))); OracleParameter[] parameters = OracleParameter[savedCount]; ) { OracleParameter oracleParameter = ” + propertyInfo.Name,propertyInfo.GetValue(obj,1)”>)); parameters[i++] = oracleParameter; } } ) { object valProVal = val.GetType().GetProperty(“).GetValue(val,1)”>); OracleParameter oracleParameter = ” + propertyInfo.Name + ++] = oracleParameter; } } } } Executesql(strsql.ToString(),parameters); } #region 修改 修改 void Update( obj) { object oldObj = Find(obj); if (oldObj == null) new Exception(无法获取到旧数据); StringBuilder strsql = update {0} object oldVal = propertyInfo.GetValue(oldObj,1)”>.Equals(oldVal,val)) { propertyNameList.Add(propertyInfo.Name); savedCount++object oldValProVal = oldVal == null ? null : oldVal.GetType().GetProperty(“).GetValue(oldVal,1)”>object valProVal = val == null : val.GetType().GetProperty(.Equals(oldValProVal,valProVal)) { propertyNameList.Add(propertyInfo.Name); savedCount++ set )); OracleParameter[] parameters = ; StringBuilder sbPros = StringBuilder(); {0}=:{0},propertyInfo.Name)); OracleParameter oracleParameter = null ? DBNull.Value : val); parameters[i++] =)); OracleParameter oracleParameter = DBNull.Value : valProVal); parameters[i++] = oracleParameter; } } } false).Length > ); null && Find(val) != ) { Update(val); } } } if (sbPros.Length > ) { strsql.Append(sbPros.ToString()); } strsql.Append( where Id={0}int.Parse(type.GetProperty(“).GetValue(obj,1)”>).ToString()))); if (savedCount > ) { Executesql(strsql.ToString(),parameters); } } #region 删除 根据Id删除 void Delete<T>( id) { Type type = (T); StringBuilder sbsql = StringBuilder(); sbsql.Append(delete from {0} where Id={1} 根据Id集合删除 void BatchDelete<T>( ids) { if (string.IsNullOrWhiteSpace(ids)) ; Type type = delete from {0} where Id in ({1})#region 获取实体 #region 根据实体获取实体 根据实体获取实体 object Find( obj) { Type type = obj.GetType(); object result = Activator.CreateInstance(type); bool hasValue = ; IDataReader rd = select * from {0} where Id={1})); { rd = ExecuteReader(sql); PropertyInfo[] propertyInfoList = type.GetProperties(); int fcnt = rd.FieldCount; List<string> fileds = (); 0; i < fcnt; i++) { fileds.Add(rd.GetName(i).ToUpper()); } (rd.Read()) { hasValue = ; IDataRecord record = rd; foreach (PropertyInfo pro propertyInfoList) { if (pro.PropertyType.IsClass) { object[] objArray = pro.GetCustomAttributes(); if (objArray.Length > ) { if (record[pro.Name + “].GetType() == typeof()) { pro.SetValue(result,record[pro.Name + “] == DBNull.Value ? null : FindById(pro.PropertyType,(int)record[pro.Name + “]),1)”>); } decimalint.Parse(((decimal)record[pro.Name + “]).ToString())),1)”>continue; } } if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value) { ; } pro.SetValue(result,record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name],pro.PropertyType),1)”>); } } } (Exception ex) { ex; } if (rd != null && !rd.IsClosed) { rd.Close(); rd.Dispose(); } } (hasValue) { result; } #region 根据Id获取实体 根据Id获取实体 object FindById(Type type,1)”> id) { Activator.CreateInstance(type); IDataReader rd = static T FindById<T>(int id) where T : () { Type type = (T); T result = (T)Activator.CreateInstance(type); IDataReader rd = (T); } } #region 获取列表 获取列表 static List<T> FindListBysql<T>(string sql) () { List<T> list = obj; IDataReader rd = ExecuteReader(sql); typeof(T) == )) { (rd.Read()) { list.Add((T)rd[]); } } else { PropertyInfo[] propertyInfoList = ((T)).GetProperties(); rd.FieldCount; List<(); ) { fileds.Add(rd.GetName(i).ToUpper()); } (rd.Read()) { IDataRecord record = rd; obj = T(); propertyInfoList) { (pro.PropertyType.IsClass) { if (pro.GetCustomAttributes() { )) { pro.SetValue(obj,1)”>); } ; } } DBNull.Value) { ; } pro.SetValue(obj,1)”>); } list.Add((T)obj); } } } #region 分页获取列表 分页(任意entity,尽量少的字段) <typeparam name=”T”></typeparam> <param name=”sql”></param> static Pageviewmodel FindPageBysql<T>(string sql,1)”>string orderby,1)”>int pageSize,1)”>int currentPage) () { Pageviewmodel pageviewmodel = Pageviewmodel(); OracleConnection(connectionString)) { connection.open(); string commandText = select count(*) from ({0}) T= = .Parse(cmd.ExecuteScalar().ToString()); int startRow = pageSize * (currentPage – ); int endRow = startRow + pageSize; StringBuilder sb = StringBuilder(); sb.Append(select * from ( select row_limit.*,rownum rownum_ from (); sb.Append(sql); string.IsNullOrWhiteSpace(orderby)) { sb.Append(” ); sb.Append(); } sb.Append( ) row_limit where rownum <= ); sb.Append(endRow); sb.Append( ) where rownum_ >); sb.Append(startRow); List<T> list = FindListBysql<T>(sb.ToString()); pageviewmodel.rows = list; } pageviewmodel; } #region getReaderValue 转换数据 转换数据 Object getReaderValue(Object rdValue,Type ptype) { if (ptype == )) Convert.ToDecimal(rdValue); Convert.ToInt32(rdValue); long Convert.ToInt64(rdValue); rdValue; } #region 事务 #region 开始事务 开始事务 BeginTransaction() { GetTran(); AddTranFlag(); } #region 结束事务(正常结束) 结束事务(正常结束) EndTransaction() { { GetTran().Commit(); RemoveTranFlag(); } (Exception ex) { GetTran().Rollback(); RemoveTranFlag(); } { GetOpenConnection().Close(); } } #region 回滚事务(出错时调用该方法回滚) 回滚事务(出错时调用该方法回滚) RollbackTransaction() { GetTran().Rollback(); RemoveTranFlag(); GetOpenConnection().Close(); } #endregion }}View Code

OracleHelper.cs(扩展修改版(扩展了几个查询方法;修改了Update方法,原方法要求实体的主键必须是Id,新方法没有此要求,但主键要加上IsId特性)):

: GetIdVal(oldVal); : GetIdVal(val); where {0}={1}.Parse(GetIdVal(obj).ToString()))); delete from {0} where {2}={1}delete from {0} where {2} in ({1}) 根据条件删除 conditions) { string.IsNullOrWhiteSpace(conditions)) delete from {0} where {1}select * from {0} where {2}={1}params OracleParameter[] cmdParms) ExecuteReader(sql,cmdParms); int currentPage,sql); OracleCommand cmd = = .Parse(cmd.ExecuteScalar().ToString()); cmd.Parameters.Clear(); (sb.ToString(),cmdParms); pageviewmodel.rows = pageviewmodel; } static DataSet FindPageBysql(int resultCount,1)”> OracleParameter[] cmdParms) { DataSet ds = = ); sb.Append(startRow); ds = Query(sql,cmdParms); } ds; } #region 获取主键名称 获取主键名称 GetIdName(Type type) { PropertyInfo[] propertyInfoList = type.GetProperties(); typeof(IsIdAttribute),1)”> propertyInfo.Name; } } ; } #region 获取主键值 object GetIdVal( val) { string idName = GetIdName(val.GetType()); .IsNullOrWhiteSpace(idName)) { return val.GetType().GetProperty(idName).GetValue(val,1)”>); } }}View Code

 辅助类代码:

NotSaveAttribute.cs:

System.Text; ORM在保存数据的时候,会忽略打上 NotSave 批注的属性 </summary> [Serializable,AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)] NotSaveAttribute : Attribute { }}View Code

IsEntityAttribute.cs:

Models{ 标识该属性是实体 IsEntityAttribute : Attribute { }}View Code

 Pageviewmodel.cs:

Models{ Pageviewmodel { 记录 public IEnumerable rows { get; set; } 记录数 int total { ; } }}View Code

 示例代码:

Models层代码:

Brand.cs:

DBUtil; Brand { int Id { ; } string Name { int BrandCount { public DateTime? BrandDate { ; } [NotSave] string NotSaved { ; } [IsEntity] public BrandChild bc { byte[] Blb { string Clb { ; } }}View Code

BrandChild.cs:

BrandChild { int Val { public BrandChildChild bcc { ; } }}View Code

BrandChildChild.cs:

BrandChildChild { ; } }}View Code

DAL层代码:

DalBase.cs:

DBUtil; Models; DAL{ DAL基类 DalBase { obj) { OracleHelper.Insert(obj); } obj) { OracleHelper.Update(obj); } 删除 id) { OracleHelper.Delete<T>(id); } 批量删除 <param name=”ids”>ID集合,逗号隔开 ids) { OracleHelper.BatchDelete<T>(ids); } 查询列表 () { return OracleHelper.FindListBysql<T>(sql); } 分页查询列表 <param name=”orderby”>例:”order by Id desc”<param name=”pageSize”>每页数据条数<param name=”currentPage”>当前页数return OracleHelper.FindPageBysql<T>(sql,pageSize,currentPage); } }}View Code

BrandDal.cs:

DAL.Admin{ Brand BrandDal : DalBase { GetNextID() { return OracleHelper.GetNextID(SEQ_BRAND); } }}View Code

Cotroller层测试代码片段:

Run() { #region 添加 ) { OracleHelper.BeginTransaction(); 子表的子表 BrandChildChild bcc1 = BrandChildChild(); bcc1.Id = BrandDal.GetNextID(); bcc1.Name = bcc1 DateTime.Now.ToString(); BrandDal.Insert(bcc1); 子表 BrandChild bc1 = BrandChild(); bc1.Id = BrandDal.GetNextID(); bc1.Name = bc1 DateTime.Now.ToString(); bc1.bcc = bcc1; OracleHelper.Insert(bc1); 主表 Brand bd1 = Brand(); bd1.Id = BrandDal.GetNextID(); bd1.Name = bd1 DateTime.Now.ToString(); bd1.bc = bc1; OracleHelper.Insert(bd1); OracleHelper.EndTransaction(); } (Exception ex) { OracleHelper.RollbackTransaction(); } } #endregion #region 修改 替换子表 BrandChild bc1 = DateTime.Now.ToString(); OracleHelper.Insert(bc1); 更新主表 Brand bd1 = OracleHelper.FindById<Brand>(27); bd1.Name = bc1; OracleHelper.Update(bd1); OracleHelper.EndTransaction(); } #region 删除 { OracleHelper.Delete<Brand>(21); OracleHelper.BatchDelete<Brand>(22,23); OracleHelper.EndTransaction(); } #region 大文本 ) { Brand bd1 = OracleHelper.FindById<Brand>(); bd1.Blb = Encoding.Default.GetBytes(大家好!); bd1.Clb = ; OracleHelper.Update(bd1); Brand bd12 = OracleHelper.FindById<Brand>(#region 查询列表 List<Brand> brandList = BrandDal.FindListBysql<Brand>(select * from BRAND); #region 分页查询列表 Pageviewmodel pageviewmodel = BrandDal.FindPageBysql<Brand>(order by Id desc10,1)”> }View Code