首页 > 代码库 > 轻量级ORM

轻量级ORM

1.下载 http://git.oschina.net/wangwei123/easy4net

2.修改成仅支持sql server

a.删除DBUtility.DatabaseType.cs; DBUtility.DbTypeConvert.cs

b.修改相关代码

DBUtility.DbFactory

using System;using System.Configuration;using System.Data;using System.Collections;using System.Data.SqlClient;namespace Easy4net.DBUtility{    public class DbFactory    {        public static IDbConnection CreateDbConnection(string connectionString)        {            return new SqlConnection(connectionString); ;        }        public static IDbCommand CreateDbCommand()        {            return new SqlCommand();        }        public static IDbDataAdapter CreateDataAdapter()        {            return new SqlDataAdapter();        }        public static IDbDataAdapter CreateDataAdapter(IDbCommand cmd)        {            return new SqlDataAdapter((SqlCommand)cmd);        }        public static IDbDataParameter CreateDbParameter()        {            return new SqlParameter();        }        public static IDbDataParameter CreateDbParameter(string paramName, object value)        {            IDbDataParameter param = DbFactory.CreateDbParameter();            param.ParameterName = paramName;            param.Value = value;            return param;        }        public static IDbDataParameter CreateDbParameter(string paramName, object value, DbType dbType)        {            IDbDataParameter param = DbFactory.CreateDbParameter();            param.DbType = dbType;            param.ParameterName = paramName;            param.Value = value;            return param;        }        public static IDbDataParameter CreateDbParameter(string paramName, object value, ParameterDirection direction)        {            IDbDataParameter param = DbFactory.CreateDbParameter();            param.Direction = direction;            param.ParameterName = paramName;            param.Value = value;            return param;        }        public static IDbDataParameter CreateDbParameter(string paramName, object value, int size, ParameterDirection direction)        {            IDbDataParameter param = DbFactory.CreateDbParameter();            param.Direction = direction;            param.ParameterName = paramName;            param.Value = value;            param.Size = size;            return param;        }        public static IDbDataParameter CreateDbOutParameter(string paramName, int size)        {            IDbDataParameter param = DbFactory.CreateDbParameter();            param.Direction = ParameterDirection.Output;            param.ParameterName = paramName;            param.Size = size;            return param;        }        public static IDbDataParameter CreateDbParameter(string paramName, object value, DbType dbType, ParameterDirection direction)        {            IDbDataParameter param = DbFactory.CreateDbParameter();            param.Direction = direction;            param.DbType = dbType;            param.ParameterName = paramName;            param.Value = value;            return param;        }        public static IDbDataParameter[] CreateDbParameters(int size)        {            int i = 0;            IDbDataParameter[] param = new SqlParameter[size];            while (i < size) { param[i] = new SqlParameter(); i++; }            return param;        }        public static IDbTransaction CreateDbTransaction()        {            IDbConnection conn = CreateDbConnection(AdoHelper.ConnectionString);            if (conn.State == ConnectionState.Closed)            {                conn.Open();            }            return conn.BeginTransaction();        }    }}
View Code

 

copy "DBHelper.cs" to "ORM" folder

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using Global.Utils.ORM.Common;using Global.Utils.ORM.EntityManager;using Global.Utils.ORM.DBUtility;namespace Global.Utils.ORM{    public class DBHelper    {        public IDbTransaction trans;        public EntityManager.EntityManager entityManager;        public DBHelper()        {            entityManager = EntityManagerFactory.CreateEntityManager();        }        public static DBHelper getInstance()        {            return new DBHelper();        }        public int Save<T>(T entity) where T : new()         {            if (trans != null) entityManager.Transaction = trans;            return entityManager.Save<T>(entity);        }        public int Update<T>(T entity) where T : new()         {            if (trans != null) entityManager.Transaction = trans;            return entityManager.Update<T>(entity);        }        public int Remove<T>(T entity)        {            if (trans != null) entityManager.Transaction = trans;            return entityManager.Remove<T>(entity);        }        public int Remove<T>(object id) where T : new()        {            if (trans != null) entityManager.Transaction = trans;            return entityManager.Remove<T>(id);        }        public List<T> FindAll<T>() where T : new()        {            return entityManager.FindAll<T>();        }                public List<T> FindBySql<T>(string strSql) where T : new()        {            return entityManager.FindBySql<T>(strSql);        }        public List<T> FindBySql<T>(string strSql, int pageIndex, int pageSize, string order, bool desc) where T : new()        {            return entityManager.FindBySql<T>(strSql, pageIndex, pageSize, order, desc);        }        public List<T> FindBySql<T>(string strSql, ParamMap param) where T : new()        {            return entityManager.FindBySql<T>(strSql, param);        }        public T FindById<T>(object id) where T : new()        {            return entityManager.FindById<T>(id);        }        public List<T> FindByProperty<T>(string propertyName, object propertyValue) where T : new()        {            return entityManager.FindByProperty<T>(propertyName, propertyValue);        }        public int FindCount<T>() where T : new()        {            return entityManager.FindCount<T>();        }        public int FindCount<T>(string propertyName, object propertyValue) where T : new()        {            return entityManager.FindCount<T>(propertyName, propertyValue);        }        public int FindCount<T>(DbCondition condition) where T : new()        {            return entityManager.FindCount<T>(condition);        }        public List<T> Find<T>(DbCondition condition) where T : new()        {            return entityManager.Find<T>(condition);        }        /*public List<T> Find<T>(WhereExpression where) where T : new()        {            return null;        }*/        public void BeginTransaction()        {            trans = DbFactory.CreateDbTransaction();        }        public void CommitTransaction()        {            if (trans != null)            {                trans.Commit();                trans.Dispose();                trans = null;            }        }        public void RollbackTransaction()        {            if (trans != null)            {                trans.Rollback();                trans.Dispose();                trans = null;            }        }        /*public static int Save<T>(T entity)        {            if(trans != null) em.Transaction = trans;            return em.Save<T>(entity);        }        public static int Update<T>(T entity)        {            if (trans != null) em.Transaction = trans;            return em.Update<T>(entity);        }        public static int Remove<T>(T entity)        {            if (trans != null) em.Transaction = trans;            return em.Remove<T>(entity);        }        public static int Remove<T>(object id) where T : new()        {            if (trans != null) em.Transaction = trans;            return em.Remove<T>(id);        }        public static List<T> FindAll<T>() where T : new()        {            return em.FindAll<T>();        }        public static List<T> FindBySql<T>(string strSql) where T : new()        {            return em.FindBySql<T>(strSql);        }        public static T FindById<T>(object id) where T : new()        {            return em.FindById<T>(id);        }        public static void BeginTransaction()        {            trans = DbFactory.CreateDbTransaction();        }        public static void CommitTransaction()        {            if (trans != null)            {                trans.Commit();                trans.Dispose();                trans = null;            }        }        public static void RollbackTransaction()        {            if (trans != null)            {                trans.Rollback();                trans.Dispose();                trans = null;            }        }*/    }}
View Code

 

EntityManager.EntityManagerImpl.cs

using System;using System.Collections.Generic;using System.Text;using System.Reflection;using Global.Utils.ORM.CustomAttributes;using System.Data.SqlClient;using System.Collections;using System.Data;using System.Linq;using Global.Utils.ORM.DBUtility;using Global.Utils.ORM.Common;using System.Text.RegularExpressions;namespace Global.Utils.ORM.EntityManager{    public class EntityManagerImpl : EntityManager    {        IDbTransaction transaction = null;        #region 将实体数据保存到数据库        public int Save<T>(T entity) where T : new()         {            object val = 0;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(entity.GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.INSERT, properties);                String strSql = EntityHelper.GetInsertSql(tableInfo);                strSql += EntityHelper.GetAutoSql();                IDbDataParameter[] parms = tableInfo.GetParameters();                                if (transaction != null)                     val = AdoHelper.ExecuteScalar(transaction, CommandType.Text, strSql, parms);                else                    val = AdoHelper.ExecuteScalar(AdoHelper.ConnectionString, CommandType.Text, strSql, parms);                if (Convert.ToInt32(val) > 0)                {                    PropertyInfo propertyInfo = EntityHelper.GetPrimaryKeyPropertyInfo(entity, properties);                    ReflectionHelper.SetPropertyValue(entity, propertyInfo, val);                }            }            catch (Exception e)             {                throw e;            }            return Convert.ToInt32(val);        }        #endregion        #region 将实体数据修改到数据库        public int Update<T>(T entity) where T : new()         {            object val = 0;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(entity.GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.UPDATE, properties);                String strSql = EntityHelper.GetUpdateSql(tableInfo);                IDbDataParameter[] parms = tableInfo.GetParameters();                if (transaction != null)                     val = AdoHelper.ExecuteNonQuery(transaction, CommandType.Text, strSql, parms);                else                    val = AdoHelper.ExecuteNonQuery(AdoHelper.ConnectionString, CommandType.Text, strSql, parms);            }            catch (Exception e)            {                throw e;            }            return Convert.ToInt32(val);        }        #endregion        #region 删除实体对应数据库中的数据        public int Remove<T>(T entity)        {            object val = 0;            try            {                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 =http://www.mamicode.com/ tableInfo.Id.Value;                if (transaction != null)                    val = AdoHelper.ExecuteNonQuery(transaction, CommandType.Text, strSql, parms);                else                    val = AdoHelper.ExecuteNonQuery(AdoHelper.ConnectionString, CommandType.Text, strSql, parms);            }            catch (Exception e)            {                throw e;            }            return Convert.ToInt32(val);        }        #endregion        #region 根据主键id删除实体对应数据库中的数据        public int Remove<T>(object id) where T : new()        {            object val = 0;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.DELETE, properties);                String strSql = EntityHelper.GetDeleteByIdSql(tableInfo);                IDbDataParameter[] parms = DbFactory.CreateDbParameters(1);                parms[0].ParameterName = tableInfo.Id.Key;                parms[0].Value =http://www.mamicode.com/ id;                if (transaction != null)                    val = AdoHelper.ExecuteNonQuery(transaction, CommandType.Text, strSql, parms);                else                    val = AdoHelper.ExecuteNonQuery(AdoHelper.ConnectionString, CommandType.Text, strSql, parms);            }            catch (Exception e)            {                throw e;            }            return Convert.ToInt32(val);        }        #endregion        #region 查询实体类对应的表中所有的记录数        public int FindCount<T>() where T : new()        {            int count = 0;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.COUNT, properties);                string strSql = EntityHelper.GetFindCountSql(tableInfo);                count = Convert.ToInt32(AdoHelper.ExecuteScalar(AdoHelper.ConnectionString, CommandType.Text, strSql));            }            catch (Exception ex)            {                throw ex;            }            return count;        }        #endregion        #region 根据查询条件查询实体类对应的表中的记录数        public int FindCount<T>(DbCondition condition) where T : new()        {            int count = 0;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.COUNT, properties);                tableInfo.Columns = condition.Columns;                string strSql = EntityHelper.GetFindCountSql(tableInfo, condition);                count = Convert.ToInt32(AdoHelper.ExecuteScalar(AdoHelper.ConnectionString, CommandType.Text, strSql, tableInfo.GetParameters()));            }            catch (Exception ex)            {                throw ex;            }            return count;        }        #endregion         #region 根据一个查询条件查询实体类对应的表中所有的记录数        public int FindCount<T>(string propertyName, object propertyValue) where T : new()        {            int count = 0;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.COUNT, properties);                string strSql = EntityHelper.GetFindCountSql(tableInfo);                strSql += string.Format(" WHERE {0} = @{1}", propertyName, propertyName);                ColumnInfo columnInfo = new ColumnInfo();                columnInfo.Add(propertyName, propertyValue);                IDbDataParameter[] parameters = DbFactory.CreateDbParameters(1);                EntityHelper.SetParameters(columnInfo, parameters);                count = Convert.ToInt32(AdoHelper.ExecuteScalar(AdoHelper.ConnectionString, CommandType.Text, strSql, parameters));            }            catch (Exception ex)            {                throw ex;            }            return count;        }        #endregion        #region 查询实体对应表的所有数据        public List<T> FindAll<T>() where T : new()        {            IDataReader sdr = null;            List<T> list = new List<T>();            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.SELECT, properties);                String strSql = EntityHelper.GetFindAllSql(tableInfo).ToUpper();                sdr = AdoHelper.ExecuteReader(AdoHelper.ConnectionString, CommandType.Text, strSql);                list = EntityHelper.toList<T>(sdr, tableInfo, properties);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (sdr != null) sdr.Close();            }            return list;        }        #endregion        #region 通过自定义条件查询数据        public List<T> Find<T>(DbCondition condition) where T : new()        {            List<T> list = new List<T>();            IDataReader sdr = null;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.SELECT, properties);                String strSql = EntityHelper.GetFindSql(tableInfo, condition);                tableInfo.Columns = condition.Columns;                IDbDataParameter[] parameters = tableInfo.GetParameters();                sdr = AdoHelper.ExecuteReader(AdoHelper.ConnectionString, CommandType.Text, strSql, parameters);                list = EntityHelper.toList<T>(sdr, tableInfo, properties);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (sdr != null) sdr.Close();            }            return list;        }        #endregion        #region 通过自定义SQL语句查询数据        public List<T> FindBySql<T>(string strSql, int pageIndex, int pageSize, string order, bool desc) where T : new()        {            List<T> list = new List<T>();            IDataReader sdr = null;            try            {                strSql = strSql.ToLower();                String columns = SQLBuilderHelper.fetchColumns(strSql);                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.SELECT, properties);                strSql = SQLBuilderHelper.builderPageSQL(strSql, order, desc);                ParamMap param = ParamMap.newMap();                param.setPageIndex(pageIndex);                param.setPageSize(pageSize);                sdr = AdoHelper.ExecuteReader(AdoHelper.ConnectionString, CommandType.Text, strSql, param.toDbParameters());                list = EntityHelper.toList<T>(sdr, tableInfo, properties);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (sdr != null) sdr.Close();            }            return list;        }        #endregion        #region 通过自定义SQL语句查询数据        public List<T> FindBySql<T>(string strSql) where T : new()        {            List<T> list = new List<T>();            IDataReader sdr = null;            try            {                strSql = strSql.ToLower();                String columns = SQLBuilderHelper.fetchColumns(strSql);                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.SELECT, properties);                sdr = AdoHelper.ExecuteReader(AdoHelper.ConnectionString, CommandType.Text, strSql, null);                list = EntityHelper.toList<T>(sdr, tableInfo, properties);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (sdr != null) sdr.Close();            }            return list;        }        #endregion        #region 通过自定义SQL语句查询数据        public List<T> FindBySql<T>(string strSql, ParamMap param) where T : new()        {            List<T> list = new List<T>();            IDataReader sdr = null;            try            {                strSql = strSql.ToLower();                String columns = SQLBuilderHelper.fetchColumns(strSql);                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.SELECT, properties);                if (param.IsPage && !SQLBuilderHelper.isPage(strSql))                {                    strSql = SQLBuilderHelper.builderPageSQL(strSql, param.OrderFields, param.IsDesc);                }                sdr = AdoHelper.ExecuteReader(AdoHelper.ConnectionString, CommandType.Text, strSql, param.toDbParameters());                list = EntityHelper.toList<T>(sdr, tableInfo, properties);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (sdr != null) sdr.Close();            }            return list;        }        #endregion        #region 根据一个查询条件查询数据        public List<T> FindByProperty<T>(string propertyName, object propertyValue) where T : new()        {            List<T> list = new List<T>();            IDataReader sdr = null;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.SELECT, properties);                String strSql = EntityHelper.GetFindAllSql(tableInfo);                strSql += string.Format(" WHERE {0} = @{1}", propertyName, propertyName);                strSql = strSql.ToLower();                String columns = SQLBuilderHelper.fetchColumns(strSql);// strSql.Substring(0, strSql.IndexOf("FROM"));                ColumnInfo columnInfo = new ColumnInfo();                columnInfo.Add(propertyName, propertyValue);                IDbDataParameter[] parameters = DbFactory.CreateDbParameters(1);                EntityHelper.SetParameters(columnInfo, parameters);                sdr = AdoHelper.ExecuteReader(AdoHelper.ConnectionString, CommandType.Text, strSql, parameters);                list = EntityHelper.toList<T>(sdr, tableInfo, properties);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (sdr != null) sdr.Close();            }            return list;        }        #endregion        #region 通过主键ID查询数据        public T FindById<T>(object id) where T : new()        {            List<T> list = new List<T>();                       IDataReader sdr = null;            try            {                PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());                TableInfo tableInfo = EntityHelper.GetTableInfo(new T(), DbOperateType.SELECT, properties);                String strSql = EntityHelper.GetFindByIdSql(tableInfo);                IDbDataParameter[] parms = DbFactory.CreateDbParameters(1);                parms[0].ParameterName = tableInfo.Id.Key;                parms[0].Value =http://www.mamicode.com/ id;                sdr = AdoHelper.ExecuteReader(AdoHelper.ConnectionString, CommandType.Text, strSql, parms);                list = EntityHelper.toList<T>(sdr, tableInfo, properties);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (sdr != null) sdr.Close();            }            return list.FirstOrDefault();        }        #endregion                #region Transaction 注入事物对象属性        public IDbTransaction Transaction        {            get            {                return transaction;            }            set            {                transaction = value;            }        }        #endregion    }}
View Code

 

Common.SQLBuilderHelper.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Global.Utils.ORM.DBUtility;using System.Data;namespace Global.Utils.ORM.Common{    public class SQLBuilderHelper    {        private static string mssqlPageTemplate = "select {0} from (select ROW_NUMBER() OVER(order by {1}) AS RowNumber, {2}) as tmp_tbl where RowNumber BETWEEN @pageStart and @pageEnd ";        private static string mysqlOrderPageTemplate = "{0} order by {1} limit ?offset,?limit";        private static string mysqlPageTemplate = "{0} limit ?offset,?limit";        public static string fetchColumns(string strSQL)        {            String columns = strSQL.Substring(6, strSQL.IndexOf("from") - 6);            return columns;        }        public static string fetchPageBody(string strSQL)        {            string body = strSQL.Substring(6, strSQL.Length - 6);            return body;        }        public static string fetchWhere(string strSQL)        {            int index = strSQL.LastIndexOf("where");            if (index == -1) return "";            String where = strSQL.Substring(index, strSQL.Length - index);            return where;        }        public static bool isPage(string strSQL)        {             string strSql = strSQL.ToLower();            if (strSql.IndexOf("row_number()") == -1)            {                return false;            }            return true;        }        public static string builderPageSQL(string strSql, string order, bool desc)        {            string columns = fetchColumns(strSql);            string orderBy = order + (desc ? " desc " : " asc ");                        if (strSql.IndexOf("row_number()") == -1)            {                if (string.IsNullOrEmpty(order))                {                    throw new Exception(" SqlException: order field is null, you must support the order field for sqlserver page. ");                }                string pageBody = fetchPageBody(strSql);                strSql = string.Format(mssqlPageTemplate, columns, orderBy, pageBody);            }            return strSql;        }    }}
View Code

 

Common.ParamMap.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Global.Utils.ORM.Common;using System.Data;using Global.Utils.ORM.DBUtility;namespace Global.Utils.ORM.Common{    public class ParamMap : Map    {        private bool isPage;        private int pageOffset;        private int pageLimit;        private string orderFields;        private bool isDesc = true;        private ParamMap() { }        public string OrderFields        {            get { return orderFields; }            set { orderFields = value; }        }        public bool IsDesc        {            get { return isDesc; }            set { isDesc = value; }        }        public static ParamMap newMap()        {            return new ParamMap();        }        public bool IsPage        {          get           {              return isPage;          }        }        public int PageOffset        {            get            {                if (this.ContainsKey("pageIndex") && this.ContainsKey("pageSize"))                {                    int pageIndex = this.getInt("pageIndex");                    int pageSize = this.getInt("pageSize");                    if (pageIndex <= 0) pageIndex = 1;                    if (pageSize <= 0) pageSize = 1;                    return (pageIndex - 1) * pageSize;                }                return 0;            }        }        public int PageLimit        {            get            {                if (this.ContainsKey("pageSize"))                {                    return this.getInt("pageSize");                }                return 0;            }        }        public int getInt(string key)         {            var value = http://www.mamicode.com/this[key];            return Convert.ToInt32(value);        }        public String getString(string key)        {            var value = http://www.mamicode.com/this[key];            return Convert.ToString(value);        }        public Double toDouble(string key)        {            var value = http://www.mamicode.com/this[key];            return Convert.ToDouble(value);        }        public Int64 toLong(string key)        {            var value = http://www.mamicode.com/this[key];            return Convert.ToInt64(value);         }        public Decimal toDecimal(string key)        {            var value = http://www.mamicode.com/this[key];            return Convert.ToDecimal(value);        }        public DateTime toDateTime(string key)        {            var value = http://www.mamicode.com/this[key];            return Convert.ToDateTime(value);        }        public void setOrderFields(string orderFields, bool isDesc)        {            this.orderFields = orderFields;            this.isDesc = isDesc;        }                public void setPageIndex(int pageIndex)         {            this["pageIndex"] = pageIndex;            setPages();        }        public void setPageSize(int pageSize)        {            this["pageSize"] = pageSize;            setPages();        }       public void setPages()         {            if (this.ContainsKey("pageIndex") && this.ContainsKey("pageSize"))            {                this.isPage = true;                int pageIndex = this.getInt("pageIndex");                int pageSize = this.getInt("pageSize");                if (pageIndex <= 0) pageIndex = 1;                if (pageSize <= 0) pageSize = 1;                this["pageStart"] = (pageIndex - 1) * pageSize + 1;                this["pageEnd"] = pageIndex * pageSize;                this.Remove("pageIndex");                this.Remove("pageSize");            }        }        public IDbDataParameter[] toDbParameters()        {            int i = 0;            IDbDataParameter[] paramArr = DbFactory.CreateDbParameters(this.Keys.Count);            foreach(string key in this.Keys)             {                if (!string.IsNullOrEmpty(key.Trim()))                {                    object value = http://www.mamicode.com/this[key];                    if (value =http://www.mamicode.com/= null) value =http://www.mamicode.com/ DBNull.Value;                    paramArr[i].ParameterName = key;                    paramArr[i].Value = value;                    i++;                }            }            return paramArr;        }    }}
View Code

 

Common.EntityHelper.cs

using System;using System.Collections.Generic;using System.Text;using Global.Utils.ORM.CustomAttributes;using Global.Utils.ORM.DBUtility;using System.Collections;using System.Reflection;using System.Data;namespace Global.Utils.ORM.Common{    public class EntityHelper    {        private const string DbParmChar = "@";        public static string GetTableName(Type classType, DbOperateType type)        {            string strTableName = string.Empty;            string strEntityName = string.Empty;            strEntityName = classType.FullName;            object[] attr = classType.GetCustomAttributes(false);            if (attr.Length == 0) return strTableName;            foreach (object classAttr in attr)            {                if (classAttr is TableAttribute)                {                    TableAttribute tableAttr = classAttr as TableAttribute;                    strTableName = tableAttr.Name;                }            }            if (string.IsNullOrEmpty(strTableName) && (type == DbOperateType.INSERT || type == DbOperateType.UPDATE || type == DbOperateType.DELETE))            {                throw new Exception("实体类:" + strEntityName + "的属性配置[Table(name=\"tablename\")]错误或未配置");            }            return strTableName;        }        public static string GetPrimaryKey(object attribute, DbOperateType type)        {            string strPrimary = string.Empty;            IdAttribute attr = attribute as IdAttribute;            if (type == DbOperateType.INSERT)            {                switch (attr.Strategy)                {                    case GenerationType.INDENTITY:                        break;                    case GenerationType.GUID:                        strPrimary = System.Guid.NewGuid().ToString();                        break;                }            }            else {                strPrimary = attr.Name;            }            return strPrimary;        }        public static string GetColumnName(object attribute)        {            string columnName = string.Empty;            if (attribute is ColumnAttribute)            {                ColumnAttribute columnAttr = attribute as ColumnAttribute;                columnName = columnAttr.Name;            }            if (attribute is IdAttribute)            {                IdAttribute idAttr = attribute as IdAttribute;                columnName = idAttr.Name;            }            return columnName;        }        public static TableInfo GetTableInfo(object entity, DbOperateType dbOpType, PropertyInfo[] properties)        {            bool breakForeach = false;            string strPrimaryKey = string.Empty;            TableInfo tableInfo = new TableInfo();            Type type = entity.GetType();            tableInfo.TableName = GetTableName(type, dbOpType);            if (dbOpType == DbOperateType.COUNT)            {                return tableInfo;            }                        foreach (PropertyInfo property in properties)            {                object propvalue = http://www.mamicode.com/null;                string columnName = string.Empty;                string propName = columnName = property.Name;                          propvalue = ReflectionHelper.GetPropertyValue(entity, property);                object[] propertyAttrs = property.GetCustomAttributes(false);                for (int i = 0; i < propertyAttrs.Length; i++)                {                    object propertyAttr = propertyAttrs[i];                    if (EntityHelper.IsCaseColumn(propertyAttr, dbOpType))                    {                        breakForeach = true;break;                    }                    string tempVal = GetColumnName(propertyAttr);                    columnName = tempVal == string.Empty ? propName : tempVal;                    if (propertyAttr is IdAttribute)                    {                        if (dbOpType == DbOperateType.INSERT || dbOpType == DbOperateType.DELETE)                        {                            IdAttribute idAttr = propertyAttr as IdAttribute;                            tableInfo.Strategy = idAttr.Strategy;                            if (CommonUtils.IsNullOrEmpty(propvalue))                            {                                strPrimaryKey = EntityHelper.GetPrimaryKey(propertyAttr, dbOpType);                                if (!string.IsNullOrEmpty(strPrimaryKey))                                    propvalue = strPrimaryKey;                            }                        }                        tableInfo.Id.Key = columnName;                        tableInfo.Id.Value = propvalue;                        tableInfo.PropToColumn.Put(propName, columnName);                        breakForeach = true;                    }                }                if (breakForeach && dbOpType == DbOperateType.DELETE) break;                if (breakForeach) { breakForeach = false; continue; }                tableInfo.Columns.Put(columnName, propvalue);                tableInfo.PropToColumn.Put(propName, columnName);            }            return tableInfo;        }        public static PropertyInfo GetPrimaryKeyPropertyInfo(object entity, PropertyInfo[] properties)        {            bool breakForeach = false;            Type type = entity.GetType();            PropertyInfo properyInfo = null;            foreach (PropertyInfo property in properties)            {                string columnName = string.Empty;                string propName = columnName = property.Name;                object[] propertyAttrs = property.GetCustomAttributes(false);                for (int i = 0; i < propertyAttrs.Length; i++)                {                    object propertyAttr = propertyAttrs[i];                    if (propertyAttr is IdAttribute)                    {                        properyInfo = property;                        breakForeach = true;                        break;                    }                }                if (breakForeach) break;            }            return properyInfo;        }        public static List<T> toList<T>(IDataReader sdr, TableInfo tableInfo, PropertyInfo[] properties) where T : new()        {            List<T> list = new List<T>();                   while (sdr.Read())            {                T entity = new T();                foreach (PropertyInfo property in properties)                {                    if (tableInfo.TableName == string.Empty)                    {                        if (EntityHelper.IsCaseColumn(property, DbOperateType.SELECT)) continue;                        String name = tableInfo.PropToColumn[property.Name].ToString();                        ReflectionHelper.SetPropertyValue(entity, property, sdr[name]);                        continue;                    }                    String columnName = tableInfo.PropToColumn[property.Name].ToString();                    ReflectionHelper.SetPropertyValue(entity, property, sdr[columnName]);                }                list.Add(entity);            }            return list;        }        public static List<T> toList<T>(IDataReader sdr) where T : new()        {            List<T> list = new List<T>();            PropertyInfo[] properties = ReflectionHelper.GetProperties(new T().GetType());            while (sdr.Read())            {                T entity = new T();                foreach (PropertyInfo property in properties)                {                    String name = property.Name;                    ReflectionHelper.SetPropertyValue(entity, property, sdr[name]);                }                list.Add(entity);            }            return list;        }        public static string GetFindSql(TableInfo tableInfo, DbCondition condition)        {            StringBuilder sbColumns = new StringBuilder();            tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);            foreach (String key in tableInfo.Columns.Keys)            {                sbColumns.Append(key).Append(",");            }            if (sbColumns.Length > 0) sbColumns.Remove(sbColumns.ToString().Length - 1, 1);            string strSql = String.Empty;            if (String.IsNullOrEmpty(condition.queryString)) {                strSql = "SELECT {0} FROM {1}";                strSql = string.Format(strSql, sbColumns.ToString(), tableInfo.TableName);                strSql += condition.ToString();            }            else {                strSql = condition.ToString();            }            strSql = strSql.ToUpper();            return strSql;        }        public static string GetFindAllSql(TableInfo tableInfo)        {            StringBuilder sbColumns = new StringBuilder();            tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);            foreach (String key in tableInfo.Columns.Keys)            {                sbColumns.Append(key).Append(",");            }            if (sbColumns.Length > 0) sbColumns.Remove(sbColumns.ToString().Length - 1, 1);            string strSql = "SELECT {0} FROM {1}";            strSql = string.Format(strSql, sbColumns.ToString(), tableInfo.TableName);            return strSql;        }        public static string GetFindByIdSql(TableInfo tableInfo)        {            StringBuilder sbColumns = new StringBuilder();            if (tableInfo.Columns.ContainsKey(tableInfo.Id.Key))                tableInfo.Columns[tableInfo.Id.Key] = tableInfo.Id.Value;            else                tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);            foreach (String key in tableInfo.Columns.Keys)            {                sbColumns.Append(key).Append(",");            }            if (sbColumns.Length > 0) sbColumns.Remove(sbColumns.ToString().Length - 1, 1);            string strSql = "SELECT {0} FROM {1} WHERE {2} = " + DbParmChar + "{2}";            strSql = string.Format(strSql, sbColumns.ToString(), tableInfo.TableName, tableInfo.Id.Key);            return strSql;        }        public static string GetFindCountSql(TableInfo tableInfo)        {            StringBuilder sbColumns = new StringBuilder();            string strSql = "SELECT COUNT(0) FROM {1} ";            strSql = string.Format(strSql, sbColumns.ToString(), tableInfo.TableName);            foreach (String key in tableInfo.Columns.Keys)            {                sbColumns.Append(key).Append("=").Append(DbParmChar).Append(key);            }            if (sbColumns.Length > 0)            {                strSql += " WHERE " + sbColumns.ToString();            }            return strSql;        }        public static string GetFindCountSql(TableInfo tableInfo, DbCondition condition)        {            string strSql = "SELECT COUNT(0) FROM {0}";            strSql = string.Format(strSql, tableInfo.TableName);            strSql += condition.ToString();            return strSql;        }        public static string GetFindByPropertySql(TableInfo tableInfo)        {            StringBuilder sbColumns = new StringBuilder();            tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);            foreach (String key in tableInfo.Columns.Keys)            {                sbColumns.Append(key).Append(",");            }            if (sbColumns.Length > 0) sbColumns.Remove(sbColumns.ToString().Length - 1, 1);            string strSql = "SELECT {0} FROM {1} WHERE {2} = " + DbParmChar + "{2}";            strSql = string.Format(strSql, sbColumns.ToString(), tableInfo.TableName, tableInfo.Id.Key);            return strSql;        }        public static string GetAutoSql()        {            return " select scope_identity() as AutoId ";        }        public static string GetInsertSql(TableInfo tableInfo)        {            StringBuilder sbColumns = new StringBuilder();            StringBuilder sbValues = new StringBuilder();            if(tableInfo.Strategy != GenerationType.INDENTITY)                tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);                        foreach (String key in tableInfo.Columns.Keys)            {                Object value = tableInfo.Columns[key];                if (!string.IsNullOrEmpty(key.Trim()) && value != null)                {                    sbColumns.Append(key).Append(",");                    sbValues.Append(DbParmChar).Append(key).Append(",");                }            }            if (sbColumns.Length > 0 && sbValues.Length > 0)            {                sbColumns.Remove(sbColumns.ToString().Length - 1, 1);                sbValues.Remove(sbValues.ToString().Length - 1, 1);            }            string strSql = "INSERT INTO {0}({1}) VALUES({2})";            strSql = string.Format(strSql, tableInfo.TableName, sbColumns.ToString(), sbValues.ToString());            return strSql;        }        public static string GetUpdateSql(TableInfo tableInfo)        {            StringBuilder sbBody = new StringBuilder();                        foreach (String key in tableInfo.Columns.Keys)            {                Object value = tableInfo.Columns[key];                if (!string.IsNullOrEmpty(key.Trim()) && value != null)                {                    sbBody.Append(key).Append("=").Append(DbParmChar + key).Append(",");                }            }            if (sbBody.Length > 0) sbBody.Remove(sbBody.ToString().Length - 1, 1);            tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);            string strSql = "update {0} set {1} where {2} =" + DbParmChar + tableInfo.Id.Key;            strSql = string.Format(strSql, tableInfo.TableName, sbBody.ToString(), tableInfo.Id.Key);            return strSql;        }        public static string GetDeleteByIdSql(TableInfo tableInfo)        {            string strSql = "delete from {0} where {1} =" + DbParmChar + tableInfo.Id.Key;            strSql = string.Format(strSql, tableInfo.TableName, tableInfo.Id.Key);            return strSql;        }        public static void SetParameters(ColumnInfo columns, params IDbDataParameter[] parms)        {            int i = 0;            foreach (string key in columns.Keys)            {                if (!string.IsNullOrEmpty(key.Trim()))                {                    object value =http://www.mamicode.com/ columns[key];                    if (value =http://www.mamicode.com/= null) value =http://www.mamicode.com/ DBNull.Value;                    parms[i].ParameterName = key;                    parms[i].Value = value;                    i++;                }            }        }        public static bool IsCaseColumn(object attribute, DbOperateType dbOperateType)        {            if (attribute is ColumnAttribute)            {                ColumnAttribute columnAttr = attribute as ColumnAttribute;                if (columnAttr.Ignore)                {                    return true;                }                if (!columnAttr.IsInsert && dbOperateType == DbOperateType.INSERT)                {                    return true;                }                if (!columnAttr.IsUpdate && dbOperateType == DbOperateType.UPDATE)                {                    return true;                }             }            return false;        }        public static bool IsCaseColumn(PropertyInfo property, DbOperateType dbOperateType)        {            bool isBreak = false;            object[] propertyAttrs = property.GetCustomAttributes(false);            foreach (object propertyAttr in propertyAttrs)            {                if (EntityHelper.IsCaseColumn(propertyAttr, DbOperateType.SELECT))                {                    isBreak = true; break;                }            }            return isBreak;        }    }}
View Code

 

c. replace "Easy4net" to "Global.Utils.ORM"