轻量级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();
        }
    }
}

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;
            }
        }*/
    }
}

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 = 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 = 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 = 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
    }
}

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;
        }

    }
}

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 = this[key];
            return Convert.ToInt32(value);
        }

        public String getString(string key)
        {
            var value = this[key];
            return Convert.ToString(value);
        }

        public Double toDouble(string key)
        {
            var value = this[key];
            return Convert.ToDouble(value);
        }

        public Int64 toLong(string key)
        {
            var value = this[key];
            return Convert.ToInt64(value);
        }

        public Decimal toDecimal(string key)
        {
            var value = this[key];
            return Convert.ToDecimal(value);
        }

        public DateTime toDateTime(string key)
        {
            var value = 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 = this[key];
                    if (value == null) value = DBNull.Value;
                    paramArr[i].ParameterName = key;
                    paramArr[i].Value = value;
                    i++;
                }
            }

            return paramArr;
        }
    }
}

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 = 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 = columns[key];
                    if (value == null) value = 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;
        }
    }
}

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

轻量级ORM

时间: 2024-10-14 05:06:21

轻量级ORM的相关文章

.NET轻量级ORM组件Dapper葵花宝典

一.摘要 为什么取名叫<葵花宝典>? 从行走江湖的世界角度来讲您可以理解为一本"武功秘籍",站在我们IT编程的世界角度应该叫"开发宝典". 如果您在工作中主要接触的是操作MySQL数据库,但您又想学习和了解.NET轻量级ORM框架Dapper,那么就请跟着阿笨一起学习本次的分享课<.NET轻量级ORM框架Dapper葵花宝典>.Let's Go,Do It ,Dapper For MySQL! 废话不多说,直接上干货,我们不生产干货,我们只是

c# 轻量级ORM框架 实现(一)

发布一个自己写的一个轻量级ORM框架,本框架设计期初基于三层架构.所以从命名上来看,了解三层的朋友会很好理解. 设计该框架的目的:不想重复的写增删改查,把精力放到功能实现上. 发布改框架的原因:希望给初学者一个参考,希望能给予好的建议,给自己一个展示机会. 在我开始之前,先说明一下,我对"软件工程学"概念东西几乎不通,最高文化程度:初二,所以不喜勿喷. 开始我的orm设计最底层 最底层的是一个DalBase,它是一个抽象的,实现了增删改查的基本操作. 它既然是一个抽象的,那么它的内部就

.NET轻量级ORM组件Dapper修炼手册

一.摘要 1.1.为什么叫本次的分享课叫<修炼手册>? 阿笨希望本次的分享课中涉及覆盖的一些小技巧.小技能给您带来一些帮助.希望您在日后工作中把它作为一本实际技能手册进行储备,以备不时之需,一旦当手头遇到与Dapper修炼手册中相似用法的地方和场景,可以直接拿来进行翻阅并灵活的运用到项目中.最后阿笨建议您可以根据自己在工作中碰到的不同的使用场景,不断的完善此本修炼手册. 废话不多说,直接上干货,我们不生产干货,我们只是干货的搬运工. 四.涉及覆盖的知识点 1.C# Linq To Xml技术.

轻量级ORM框架初探-Dapper与PetaPoco的基本使用

一.EntityFramework EF是传统的ORM框架,也是一个比较重量级的ORM框架.这里仍然使用EF的原因在于为了突出轻量级ORM框架的性能,所谓有对比才有更优的选择. 1.1 准备一张数据库表 (1)For MSSQL CREATE TABLE [dbo].[Posts] ( [Id] INT NOT NULL PRIMARY KEY IDENTITY, [CategoryId] INT NOT NULL, [Slug] VARCHAR(120) NOT NULL, [Title] N

c# 轻量级 ORM 框架 之 DBHelper 实现 (三)

周末了比较清闲,把自己的orm框架整理了下,开源了. 已经做出来的东西通常感觉有些简单,一些新手或许听到"框架"一类的词觉得有些"高深",简单来说orm就是把ado的封装. 在介绍这个框架的第一篇博文,已经把DalBase介绍了一下设计思路,本篇的DBHelper对象也是给dalBase来用的,可以说框架的所有定义对象都是为了它. 这里起名叫DBHelper,因为我也是从写SQLHelper开始的,DBHelper只不过是所有类型对ado操作的各种方法的封装,所以本

.NET轻量级ORM框架Dapper修炼手册

一.摘要 1.1.为什么叫本次的分享课叫<修炼手册>? 阿笨希望本次的分享课中涉及覆盖的一些小技巧.小技能给您带来一些帮助.希望您在日后工作中把它作为一本实际技能手册进行储备,以备不时之需,一旦当手头遇到与Dapper修炼手册中相似用法的地方和场景,可以直接拿来进行翻阅并灵活的运用到项目中.最后阿笨建议您可以根据自己在工作中碰到的不同的使用场景,不断的完善此本修炼手册. 废话不多说,直接上干货,我们不生产干货,我们只是干货的搬运工. 四.涉及覆盖的知识点 1.C# Linq To Xml技术.

jdao 1.1 发布,轻量级 ORM 工具包

jdao 1.1 发布了,更新内容如下: 修复了一些bug,增加支持 is null ,is not null等对应的方法. jdao是一个Java的轻量级orm工具包,根据表名可以生成与之对应的dao类,同时也支持原生sql语句操作(入门教程qkxue.net). 下载地址: https://github.com/donnie4w/jdao/archive/master.zip

Farseer.net轻量级ORM开源框架 V1.x 入门篇:数据库上下文

导航 目   录:Farseer.net轻量级ORM开源框架 目录 上一篇:Farseer.net轻量级ORM开源框架 V1.x 入门篇:数据库配置文件 下一篇:Farseer.net轻量级ORM开源框架 V1.x 入门篇:表实体类映射 前言 上文讲述了数据库配置使用,搭建好数据库的链接方式了我们知道怎么做了. 事实上,至今我们仍然还没有讲到代码方面,花了前面这么多篇幅讲解,主要是想由浅入深,不然一上来给大家讲解这讲解那的,听的也一头雾水,反而得不到效果. 这篇比较重要,因为它是我们在使用Far

c# 轻量级ORM框架 之 WhereHelper (二)

上篇文章发布了一些设计orm框架基层的和实现,有朋友提出WhereHelper是亮点,能被认可我表示高兴. 我就把WhereHelper设计思想和代码公开下. WhereHelper 的概念就是再拼接where 条件,为了能兼容各种数据库和参数化查询,故封装了该对象. 首先根据我的框架结构: 1.Common库 这里主要定义了,所有层都访问的类型及常用方法,因为是介绍WhereHelper的实现,对其它就不做详细解释了. WhereHelper定义到这一层是想着UI会用到该查询,故把该类型的定义