自己写的.net ORM 框架

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Mines
{
    public static class Lavery
    {
        #region ORM
        #region 属性
        private static readonly Hashtable htSql = Hashtable.Synchronized(new Hashtable(10240));

        /// <summary>
        /// 表前缀
        /// </summary>
        private static readonly string TbPrefix = ConfigurationManager.AppSettings["TbPrefix"];

        /// <summary>
        /// 数据库类型 支持MySql,MSSQL,OleDb
        /// </summary>
        private static readonly string Dbtype = ConfigurationManager.AppSettings["Dbtype"];

        /// <summary>
        /// 默认数据库连接字符串
        /// </summary>
        private static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        #endregion

        #region Exists
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public static bool Exists<T>(int id)
        {
            return Exists(string.Format("select count(0) from {0} where [email protected]", TbPrefix + typeof(T).Name), new DbParameter[] { Parameter("id", id) });
        }

        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool Exists<T>(string connstr, int id)
        {
            return Exists(connstr, string.Format("select count(0) from {0} where [email protected]", TbPrefix + typeof(T).Name), new DbParameter[] { Parameter("id", id) });
        }
        #endregion

        #region GetCount
        /// <summary>
        /// 查询个数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public static int GetCount<T>(string strWhere)
        {
            return Convert.ToInt32(ExecuteScalar(string.Format("select count(0) from {0} {1}", TbPrefix + typeof(T).Name, !string.IsNullOrEmpty(strWhere) ? " where " + strWhere : "")));
        }
        /// <summary>
        /// 查询个数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public static int GetCount<T>(string connstr, string strWhere)
        {
            return Convert.ToInt32(ExecuteScalar(connstr, string.Format("select count(0) from {0} {1}", TbPrefix + typeof(T).Name, !string.IsNullOrEmpty(strWhere) ? " where " + strWhere : "")));
        }

        /// <summary>
        /// 查询个数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strWhere"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static int GetCount<T>(string strWhere, params DbParameter[] param)
        {
            return Convert.ToInt32(ExecuteScalar(string.Format("select count(0) from {0} {1}", TbPrefix + typeof(T).Name, !string.IsNullOrEmpty(strWhere) ? " where " + strWhere : ""), param));
        }

        /// <summary>
        /// 查询个数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="strWhere"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static int GetCount<T>(string connstr, string strWhere, params DbParameter[] param)
        {
            return Convert.ToInt32(ExecuteScalar(connstr, string.Format("select count(0) from {0} {1}", TbPrefix + typeof(T).Name, !string.IsNullOrEmpty(strWhere) ? " where " + strWhere : ""), param));
        }

        #endregion

        #region Add
        public static int Add<T>(T model)
        {
            return Add<T>(null, model);
        }

        public static int Add<T>(string connstr, T model)
        {
            List<DbParameter> parameters;
            string sql = GetAddSqlAndParams<T>(model, out parameters);
            if (string.IsNullOrEmpty(sql))
                return 0;
            var r = ExecuteScalar(connstr, sql, parameters.ToArray());
            return r == null ? 0 : Convert.ToInt32(r);
        }

        public static int Add<T>(DbConnection connection, DbTransaction trans, T model)
        {
            List<DbParameter> parameters;
            string sql = GetAddSqlAndParams<T>(model, out parameters);

            if (string.IsNullOrEmpty(sql))
                return 0;
            var r = ExecuteScalar(sql, connection, trans, parameters.ToArray());
            return r == null ? 0 : Convert.ToInt32(r);
        }

        public static string GetAddSqlAndParams<T>(T model, out List<DbParameter> parameters)
        {
            var t = typeof(T);
            parameters = new List<DbParameter>();
            string sql = (string)htSql[t.Name + "Add"];
            var PropertyInfos = (PropertyInfo[])htSql[t.Name + "PropertyInfo[]"];
            if (PropertyInfos == null)
            {
                PropertyInfos = t.GetProperties();
                htSql[t.Name + "PropertyInfo[]"] = PropertyInfos;
            }
            if (!string.IsNullOrEmpty(sql))
            {
                foreach (var p in PropertyInfos)
                {
                    object v = p.GetValue<T>(model);

                    if (p.Name.ToLower().Equals("id") && v != null) continue;

                    if (p.GetCustomAttributes(typeof(NotDBFieldAttribute), false).Length == 0)
                    {
                        if (p.GetCustomAttributes(typeof(SerialAttribute), false).Length > 0)
                            parameters.Add(p.Parameter(SerializeObject(v)));
                        else
                            parameters.Add(p.Parameter(v));
                    }
                }
            }
            else
            {
                List<string> field = new List<string>();
                foreach (var p in PropertyInfos)
                {
                    object v = p.GetValue<T>(model);
                    if (p.Name.ToLower().Equals("id") && v != null) continue;
                    if (p.GetCustomAttributes(typeof(NotDBFieldAttribute), false).Length == 0)
                    {
                        if (p.GetCustomAttributes(typeof(SerialAttribute), false).Length > 0)
                            parameters.Add(p.Parameter(SerializeObject(v)));
                        else
                            parameters.Add(p.Parameter(v));
                        field.Add(p.Name);
                    }
                }

                sql = string.Format("insert into {0}{1} ([{2}]) values (@{3});select @@IDENTITY", TbPrefix, t.Name, string.Join("],[", field), string.Join(",@", field));
                htSql[t.Name + "Add"] = sql;
            }
            return sql;
        }
        #endregion

        #region Update
        public static bool Update<T>(T model)
        {
            return Update<T>(null, model);
        }
        public static bool Update<T>(string connstr, T model)
        {
            List<DbParameter> parameters;
            string sql = GetUpdateSqlAndParams<T>(model, out parameters);
            return ExecuteNonQuery(connstr, sql, parameters.ToArray()) > 0;
        }

        public static bool Update<T>(DbConnection conn, DbTransaction trans, T model)
        {
            List<DbParameter> parameters;
            string sql = GetUpdateSqlAndParams<T>(model, out parameters);
            return ExecuteNonQuery(sql, conn, trans, parameters.ToArray()) > 0;
        }
        public static bool UpdateField<T>(string where, string value)
        {
            return UpdateField<T>(null, where, value);
        }

        public static bool UpdateField<T>(string connstr, string where, string value)
        {
            return ExecuteNonQuery(connstr, string.Format("update {1} set {0} where {2}", value, TbPrefix + typeof(T).Name, where)) > 0;

        }

        public static bool UpdateField<T>(DbConnection conn, DbTransaction trans, string where, string value)
        {
            return ExecuteNonQuery(string.Format("update {1} set {0} where {2}", value, TbPrefix + typeof(T).Name, where), conn, trans) > 0;
        }
        public static string GetUpdateSqlAndParams<T>(T model, out List<DbParameter> parameters)
        {
            parameters = new List<DbParameter>();
            var t = typeof(T);
            string sql = (string)htSql[t.Name + "Update"];
            var PropertyInfos = (PropertyInfo[])htSql[t.Name + "PropertyInfo[]"];
            if (PropertyInfos == null)
            {
                PropertyInfos = t.GetProperties();
                htSql[t.Name + "PropertyInfo[]"] = PropertyInfos;
            }
            if (!string.IsNullOrEmpty(sql))
                foreach (var p in PropertyInfos)
                {
                    if (p.GetCustomAttributes(typeof(NotDBFieldAttribute), false).Length == 0)
                    {
                        if (p.GetCustomAttributes(typeof(SerialAttribute), false).Length > 0)
                            parameters.Add(p.Parameter(SerializeObject(p.GetValue(model))));
                        else
                            parameters.Add(p.Parameter(p.GetValue(model)));
                    }
                }
            else
            {
                List<string> strField = new List<string>();
                string where = string.Empty;
                foreach (var p in PropertyInfos)
                {
                    if (p.GetCustomAttributes(typeof(NotDBFieldAttribute), false).Length == 0)
                    {
                        if (p.GetCustomAttributes(typeof(SerialAttribute), false).Length > 0)
                            parameters.Add(p.Parameter(SerializeObject(p.GetValue<T>(model))));
                        else
                            parameters.Add(p.Parameter(p.GetValue(model)));
                    }

                    if (p.Name.ToLower().Equals("id"))
                        where = string.Format(" [{0}][email protected]{0}", p.Name);
                    else
                        strField.Add(string.Format(" [{0}][email protected]{0}", p.Name));
                }
                sql = string.Format("update {1}{2} set {0} where {3}", string.Join(",", strField), TbPrefix, t.Name, where);
                htSql[t.Name + "Update"] = sql;
            }
            return sql;
        }
        #endregion

        #region Delete
        public static bool Delete<T>(string where)
        {
            return ExecuteNonQuery(string.Format("delete from {0} where {1}", TbPrefix + typeof(T).Name, where)) > 0;
        }
        public static bool Delete<T>(string connstr, string where)
        {
            return ExecuteNonQuery(connstr, string.Format("delete from {0} where {1}", TbPrefix + typeof(T).Name, where)) > 0;
        }
        public static bool Delete<T>(DbConnection conn, DbTransaction trans, string where)
        {
            return ExecuteNonQuery(string.Format("delete from {0} where {1}", TbPrefix + typeof(T).Name, where), conn, trans) > 0;
        }
        #endregion

        #region GetModel
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T GetModel<T>(int id)
        {
            return GetModel<T>(null, id);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T GetModel<T>(string connstr, int id)
        {
            List<DbParameter> parameters = new List<DbParameter>();
            parameters.Add(Parameter("id", id));
            string StrSql = string.Format("select * from {0} where id={1} ", TbPrefix + typeof(T).Name, id);
            var reader = ExecuteReader(connstr, StrSql, parameters.ToArray());
            while (reader.Read())
            {
                return GetModel<T>(reader);
            }
            reader.Close();
            return default(T);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T GetModel<T>(string where, params DbParameter[] param)
        {
            return GetModel<T>(null, where, param);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T GetModel<T>(string connstr, string where, params DbParameter[] param)
        {
            var StrSql = string.Format("select top 1 * from {0} where {1} ", TbPrefix + typeof(T).Name, where);
            var reader = ExecuteReader(connstr, StrSql, param);
            T o = default(T);
            while (reader.Read())
            {
                o = GetModel<T>(reader, o, typeof(T));
                break;
            }
            reader.Close();
            return o;
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static T GetModel<T>(IDataReader reader)
        {
            var type = typeof(T);
            return GetModel<T>(reader, default(T), type);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <param name="o"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T GetModel<T>(IDataReader reader, T o, Type t)
        {
            if (o == null)
                o = (T)Activator.CreateInstance(t);
            var PropertyInfos = (PropertyInfo[])htSql[t.Name + "PropertyInfo[]"];
            if (PropertyInfos == null)
            {
                PropertyInfos = t.GetProperties();
                htSql[t.Name + "PropertyInfo[]"] = PropertyInfos;
            }
            foreach (var p in PropertyInfos)
            {
                if (!reader[p.Name].Equals(DBNull.Value))
                {
                    if (p.GetCustomAttributes(typeof(NotDBFieldAttribute), false).Length == 0)
                    {
                        if (p.GetCustomAttributes(typeof(SerialAttribute), false).Length > 0)
                            p.SetValue<T>(o, DeserializeObject(reader[p.Name].ToString()));
                        else
                            p.SetValue<T>(o, reader[p.Name]);
                    }
                }
            }
            return o;
        }

        #endregion

        #region Query
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pageSize"></param>
        /// <param name="currentPage"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <returns></returns>
        public static DataSet Query<T>(int pageSize, int currentPage, string strWhere, string filedOrder)
        {
            int topSize = pageSize * currentPage;
            StringBuilder strSql = new StringBuilder();
            if (Dbtype == "MySql")
            {
                strSql.AppendFormat("select * from {0}", TbPrefix + typeof(T).Name);
                if (!string.IsNullOrEmpty(strWhere)) strSql.Append(" where " + strWhere);
                if (!string.IsNullOrEmpty(filedOrder)) strSql.Append(" order by " + filedOrder);
                strSql.AppendFormat(" limit {0},{1}", topSize, pageSize);
            }
            else
            {
                strSql.Append("select top " + pageSize + " * from " + TbPrefix + typeof(T).Name);
                strSql.AppendFormat(" where Id not in(select top {0} Id from {1}", topSize, TbPrefix + typeof(T).Name);
                if (strWhere.Trim() != "") strSql.Append(" where " + strWhere);
                if (!string.IsNullOrEmpty(filedOrder)) strSql.Append(" order by " + filedOrder);
                if (strWhere.Trim() != "") strSql.Append(" and " + strWhere);
                if (!string.IsNullOrEmpty(filedOrder)) strSql.Append(" order by " + filedOrder);
            }
            return Query(strSql.ToString());
        }

        #endregion

        #region GetList
        /// <summary>
        /// 返回T的集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strSQL"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(string strSQL)
        {
            return GetList<T>(null, strSQL);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="strSQL"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(string connstr, string strSQL)
        {
            var myReader = ExecuteReader(connstr, strSQL);
            while (myReader.Read())
                yield return GetModel<T>(myReader);
            myReader.Close();
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Top"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(int Top, string strWhere, string filedOrder)
        {
            return GetList<T>(null, Top, strWhere, filedOrder);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="Top"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(string connstr, int Top, string strWhere, string filedOrder)
        {
            string strsql = string.Empty;
            if (Dbtype == "MySql")
                strsql = string.Format(
                    "select * from {1} {2} {3} {0}",
                    Top > 0 ? " limit 0," + Top : "",
                    TbPrefix + typeof(T).Name,
                    !string.IsNullOrEmpty(strWhere) ? " where " + strWhere : "",
                    !string.IsNullOrEmpty(filedOrder) ? " order by " + filedOrder : ""
                    );
            else
                strsql = string.Format(
                    "select {0} * from {1} {2} {3}",
                    Top > 0 ? " top " + Top : "",
                    TbPrefix + typeof(T).Name, !string.IsNullOrEmpty(strWhere) ? " where " + strWhere : "",
                    !string.IsNullOrEmpty(filedOrder) ? " order by " + filedOrder : "");
            return GetList<T>(connstr, strsql);
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pageSize"></param>
        /// <param name="currentPage"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(int pageSize, int currentPage, string strWhere, string filedOrder)
        {
            return GetList<T>(null, pageSize, currentPage, strWhere, filedOrder);
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr">数据库连接</param>
        /// <param name="pageSize"></param>
        /// <param name="currentPage"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(string connstr, int pageSize, int currentPage, string strWhere, string filedOrder)
        {
            int topSize = pageSize * currentPage;
            StringBuilder strSql = new StringBuilder();
            if (Dbtype == "MySql")
            {
                strSql.Append("select * from " + TbPrefix + typeof(T).Name);
                if (!string.IsNullOrEmpty(strWhere)) strSql.Append(" where " + strWhere);
                if (!string.IsNullOrEmpty(filedOrder)) strSql.Append(" order by " + strWhere);
                strSql.AppendFormat(" limit {0},{1}", topSize, pageSize);
            }
            else
            {
                strSql.Append("select top " + pageSize + " * from " + TbPrefix + typeof(T).Name);
                strSql.AppendFormat(" where Id not in(select top {0} Id from {1}", topSize, TbPrefix + typeof(T).Name);
                if (strWhere.Trim() != "") strSql.Append(" where " + strWhere);
                strSql.AppendFormat(" order by {0})", !string.IsNullOrEmpty(filedOrder) ? filedOrder : "SortId asc,Id desc");
                if (strWhere.Trim() != "") strSql.Append(" and " + strWhere);
                strSql.AppendFormat(" order by {0}", !string.IsNullOrEmpty(filedOrder) ? filedOrder : "SortId asc,Id desc");
            }
            return GetList<T>(connstr, strSql.ToString());
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strSql"></param>
        /// <param name="CmdParams"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(string strSql, params DbParameter[] CmdParams)
        {
            return GetList<T>(null, strSql, CmdParams);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connstr"></param>
        /// <param name="strSql"></param>
        /// <param name="CmdParams"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(string connstr, string strSql, params DbParameter[] CmdParams)
        {
            var myReader = ExecuteReader(connstr, strSql, CmdParams);
            while (myReader.Read())
                yield return GetModel<T>(myReader);
            myReader.Close();
        }
        #endregion

        #region ADO.NET数据库操作
        #region 公用方法

        public static bool Exists(string strSql)
        {
            object obj = ExecuteScalar(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                cmdresult = 0;
            else
                cmdresult = int.Parse(obj.ToString());
            if (cmdresult == 0)
                return false;
            else
                return true;
        }

        public static bool Exists(string connstr, string strSql)
        {
            object obj = ExecuteScalar(connstr, strSql, null);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                cmdresult = 0;
            else
                cmdresult = int.Parse(obj.ToString());
            if (cmdresult == 0)
                return false;
            else
                return true;
        }

        public static bool Exists(string strSql, params DbParameter[] cmdParms)
        {
            object obj = ExecuteScalar(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                cmdresult = 0;
            else
                cmdresult = int.Parse(obj.ToString());
            if (cmdresult == 0)
                return false;
            else
                return true;
        }

        public static bool Exists(string connstr, string strSql, params DbParameter[] cmdParms)
        {
            object obj = ExecuteScalar(connstr, strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                cmdresult = 0;
            else
                cmdresult = int.Parse(obj.ToString());
            if (cmdresult == 0)
                return false;
            else
                return true;
        }
        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteNonQuery(string SQLString)
        {
            return ExecuteNonQuery(string.Empty, SQLString);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="connstr"></param>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string connstr, string SQLString)
        {
            var connection = Connection(connstr);
            var cmd = Command(SQLString, connection);
            try
            {
                connection.Open();
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (Exception e)
            {
                connection.Close();
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="connection">MySqlConnection对象</param>
        /// <param name="trans">MySqlTransaction事件</param>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteNonQuery(DbConnection connection, DbTransaction trans, string SQLString)
        {
            var cmd = Command(SQLString, connection);
            try
            {
                cmd.Connection = connection;
                cmd.Transaction = trans;
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (Exception e)
            {
                trans.Rollback();
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        public static int ExecuteNonQuery(string SQLString, int Times)
        {
            return ExecuteNonQuery(null, SQLString, Times);
        }
        public static int ExecuteNonQuery(string connstr, string SQLString, int Times)
        {
            var connection = Connection(connstr);
            var cmd = Command(SQLString, connection);
            try
            {
                connection.Open();
                cmd.CommandTimeout = Times;
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (Exception e)
            {
                connection.Close();
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>    

        public static bool ExecuteNonQuery(List<String> SQLStringList)
        {
            return ExecuteNonQuery(null, SQLStringList);
        }
        public static bool ExecuteNonQuery(string connstr, List<String> SQLStringList)
        {
            var conn = Connection(connstr);

            conn.Open();
            var cmd = Command();
            cmd.Connection = conn;
            var tx = conn.BeginTransaction();
            cmd.Transaction = tx;
            try
            {
                int count = 0;
                for (int n = 0; n < SQLStringList.Count; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Trim().Length > 1)
                    {
                        cmd.CommandText = strsql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                tx.Commit();
                return true;
            }
            catch
            {
                tx.Rollback();
                return false;
            }
            finally
            {
                conn.Close();
                cmd.Dispose();
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object ExecuteScalar(string SQLString)
        {
            return ExecuteScalar(null, SQLString);
        }
        public static object ExecuteScalar(string connstr, string SQLString)
        {
            DbConnection connection = Connection(connstr);
            DbCommand cmd = Command(SQLString, connection);
            try
            {
                connection.Open();
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    return null;
                else
                    return obj;
            }
            catch (Exception e)
            {
                connection.Close();
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        public static object ExecuteScalar(string SQLString, int Times)
        {
            return ExecuteScalar(null, SQLString, Times);
        }
        public static object ExecuteScalar(string connstr, string SQLString, int Times)
        {
            DbConnection connection = Connection(connstr);
            DbCommand cmd = Command(SQLString, connection);
            try
            {
                connection.Open();
                cmd.CommandTimeout = Times;
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    return null;
                else
                    return obj;

            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        /// <summary>
        /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>MySqlDataReader</returns>
        public static IDataReader ExecuteReader(string strSQL)
        {
            DbConnection connection = Connection();
            DbCommand cmd = Command(strSQL, connection);
            connection.Open();
            IDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Dispose();
            return myReader;
        }

        /// <summary>
        /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>MySqlDataReader</returns>
        public static IDataReader ExecuteReader(string connstr, string strSQL)
        {
            var connection = Connection(connstr);
            DbCommand cmd = Command(strSQL, connection);
            connection.Open();
            IDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Dispose();
            return myReader;
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            DbConnection connection = Connection();

            DataSet ds = new DataSet();
            try
            {
                connection.Open();
                DbDataAdapter command = DataAdapter(SQLString, connection);
                command.Fill(ds, "ds");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                connection.Close();
            }
            return ds;

        }

        public static DataSet Query(string SQLString, int Times)
        {
            DbConnection connection = Connection();
            DataSet ds = new DataSet();
            try
            {
                connection.Open();
                DbDataAdapter command = DataAdapter(SQLString, connection);
                command.SelectCommand.CommandTimeout = Times;
                command.Fill(ds, "ds");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                connection.Close();
            }
            return ds;
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="connection">DbConnection对象</param>
        /// <param name="trans">DbTransaction事务</param>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(DbConnection connection, DbTransaction trans, string SQLString)
        {
            DataSet ds = new DataSet();
            try
            {
                DbDataAdapter command = DataAdapter(SQLString, connection);
                command.SelectCommand.Transaction = trans;
                command.Fill(ds, "ds");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                connection.Close();
            }
            return ds;
        }

        public static DataSet Query(string conn, DbTransaction trans, string SQLString)
        {
            return Query(Connection(conn), trans, SQLString);
        }

        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteNonQuery(string SQLString, params DbParameter[] cmdParms)
        {
            return ExecuteNonQuery(null, SQLString, cmdParms);
        }
        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteNonQuery(string connstr, string SQLString, params DbParameter[] cmdParms)
        {
            var connection = Connection(connstr);
            var cmd = Command(SQLString, connection);

            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                int rows = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return rows;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="connection">MySqlConnection对象</param>
        /// <param name="trans">MySqlTransaction对象</param>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteNonQuery(string SQLString, DbConnection connection, DbTransaction trans, params DbParameter[] cmdParms)
        {
            var cmd = Command();
            try
            {
                PrepareCommand(cmd, connection, trans, SQLString, cmdParms);
                int rows = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return rows;
            }
            catch (Exception e)
            {
                if (trans != null)
                    trans.Rollback();
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        //public static int ExecuteNonQuery(string connstr, DbTransaction trans, string SQLString, params DbParameter[] cmdParms)
        //{
        //    return ExecuteNonQuery(Connection(connstr), trans, SQLString, cmdParms);
        //}

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
        public static int ExecuteNonQuery(Hashtable SQLStringList)
        {
            var conn = Connection();
            if (conn.State != ConnectionState.Open)
                conn.Open();
            DbTransaction trans = conn.BeginTransaction();
            var cmd = Command();
            try
            {
                int val = 0;
                foreach (DictionaryEntry myDE in SQLStringList)
                {
                    string cmdText = myDE.Key.ToString();
                    DbParameter[] cmdParms = (DbParameter[])myDE.Value;
                    PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                    val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                }
                trans.Commit();
            }
            catch
            {
                trans.Rollback();
                return 0;
            }
            finally
            {
                conn.Close();
                cmd.Dispose();
            }
            return 1;
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object ExecuteScalar(string SQLString, params DbParameter[] cmdParms)
        {
            return ExecuteScalar(null, null, SQLString, cmdParms);
        }

        public static object ExecuteScalar(string ConnStr, string SQLString, params DbParameter[] cmdParms)
        {
            return ExecuteScalar(ConnStr, null, SQLString, cmdParms);
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="connection">MySqlConnection对象</param>
        /// <param name="trans">MySqlTransaction事务</param>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object ExecuteScalar(string connstr, DbTransaction trans, string SQLString, params DbParameter[] cmdParms)
        {
            var connection = Connection(connstr);
            var cmd = Command();
            try
            {
                PrepareCommand(cmd, connection, trans, SQLString, cmdParms);
                object obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    return null;
                else
                    return obj;

            }
            catch (Exception e)
            {
                if (trans != null)
                    trans.Rollback();
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        public static object ExecuteScalar(string SQLString, DbConnection connection, DbTransaction trans, params DbParameter[] cmdParms)
        {
            var cmd = Command();
            try
            {
                PrepareCommand(cmd, connection, trans, SQLString, cmdParms);
                object obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    return null;
                else
                    return obj;

            }
            catch (Exception e)
            {
                if (trans != null)
                    trans.Rollback();
                throw e;
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
        }

        /// <summary>
        /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>MySqlDataReader</returns>
        public static IDataReader ExecuteReader(string SQLString, params DbParameter[] cmdParms)
        {
            var connection = Connection();
            var cmd = Command();
            PrepareCommand(cmd, connection, null, SQLString, cmdParms);
            IDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            cmd.Dispose();
            return myReader;
        }
        /// <summary>
        /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>MySqlDataReader</returns>
        public static IDataReader ExecuteReader(string connstr, string SQLString, params DbParameter[] cmdParms)
        {
            var cmd = Command();
            PrepareCommand(cmd, Connection(connstr), null, SQLString, cmdParms);
            IDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            cmd.Dispose();
            return myReader;
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params DbParameter[] cmdParms)
        {
            return Query(null, null, SQLString, cmdParms);
        }
        public static DataSet Query(string connstr, string SQLString, params DbParameter[] cmdParms)
        {
            return Query(connstr, null, SQLString, cmdParms);
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="connection">MySqlConnection对象</param>
        /// <param name="trans">MySqlTransaction事务</param>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string connstr, DbTransaction trans, string SQLString, params DbParameter[] cmdParms)
        {
            var connection = Connection(connstr);
            DbCommand cmd = Command();
            PrepareCommand(cmd, connection, trans, SQLString, cmdParms);
            DbDataAdapter da = DataAdapter(cmd);
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds, "ds");
                cmd.Parameters.Clear();
            }
            catch (Exception ex)
            {
                if (trans != null)
                    trans.Rollback();
                throw new Exception(ex.Message);
            }
            finally
            {
                connection.Close();
                cmd.Dispose();
            }
            return ds;
        }

        private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                trans = conn.BeginTransaction();
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (DbParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                        parameter.Value = DBNull.Value;
                    cmd.Parameters.Add(parameter);
                }
            }
        }
        private static DbConnection Connection()
        {
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlConnection(connectionString);
                case "OleDb":
                    return new MySqlConnection(connectionString);
                default:
                    return new SqlConnection(connectionString);
            }
        }

        private static DbConnection Connection(out DbTransaction trans)
        {
            DbConnection conn;
            switch (Dbtype)
            {
                case "MySql":
                    conn= new MySqlConnection(connectionString);
                    break;
                case "OleDb":
                    conn= new MySqlConnection(connectionString);
                    break;
                default:
                    conn= new SqlConnection(connectionString);
                    break;
            }
            conn.Open();
            trans = conn.BeginTransaction();
            return conn;
        }

        private static DbConnection Connection(string connstring)
        {
            if (string.IsNullOrEmpty(connstring))
                connstring = connectionString;
            else
                connstring = ConfigurationManager.ConnectionStrings["mines_" + connstring].ConnectionString;
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlConnection(connstring);
                case "OleDb":
                    return new MySqlConnection(connstring);
                default:
                    return new SqlConnection(connstring);
            }
        }

        private static DbConnection Connection(string connstring, out DbTransaction trans)
        {
            DbConnection conn;
            if (string.IsNullOrEmpty(connstring))
                connstring = connectionString;
            else
                connstring = ConfigurationManager.ConnectionStrings["mines_" + connstring].ConnectionString;
            switch (Dbtype)
            {
                case "MySql":
                    conn = new MySqlConnection(connstring);
                    break;
                case "OleDb":
                    conn = new MySqlConnection(connstring);
                    break;
                default:
                    conn = new SqlConnection(connstring);
                    break;
            }
            conn.Open();
            trans = conn.BeginTransaction();
            return conn;
        }

        private static DbCommand Command(string SQLString, DbConnection connection)
        {
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlCommand(SQLString, (MySqlConnection)connection);
                case "OleDb":
                    return new OleDbCommand(SQLString, (OleDbConnection)connection);
                default:
                    return new SqlCommand(SQLString, (SqlConnection)connection);
            }
        }
        private static DbCommand Command()
        {
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlCommand();
                case "OleDb":
                    return new OleDbCommand();
                default:
                    return new SqlCommand();
            }
        }

        private static DbDataAdapter DataAdapter(string SQLString, DbConnection connection)
        {
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlDataAdapter(SQLString, (MySqlConnection)connection);
                case "OleDb":
                    return new OleDbDataAdapter(SQLString, (OleDbConnection)connection);
                default:
                    return new SqlDataAdapter(SQLString, (SqlConnection)connection);
            }
        }

        private static DbDataAdapter DataAdapter(DbCommand cmd)
        {
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlDataAdapter((MySqlCommand)cmd);
                case "OleDb":
                    return new OleDbDataAdapter((OleDbCommand)cmd);
                default:
                    return new SqlDataAdapter((SqlCommand)cmd);
            }
        }
        #endregion
        #endregion

        #region 扩展  参数Parameter/属性读写GETVALUE、SETVALUE
        public static DbParameter Parameter(string Name, object value)
        {
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlParameter("@" + Name, value);
                case "OleDb":
                    return new OleDbParameter("@" + Name, value);
                default:
                    return new SqlParameter("@" + Name, value);
            }
        }

        public static DbParameter Parameter(this PropertyInfo p, object value)
        {
            switch (Dbtype)
            {
                case "MySql":
                    return new MySqlParameter("@" + p.Name, value);
                case "OleDb":
                    return new OleDbParameter("@" + p.Name, value);
                default:
                    return new SqlParameter("@" + p.Name, value);
            }
        }

        public static object GetValue<TModel>(this PropertyInfo p, TModel model)
        {
            var paramTmodel = Expression.Parameter(typeof(TModel), "Tmodel");

            var pGetter = Expression.Property(paramTmodel, p);

            var returnObj = Expression.Convert(pGetter, typeof(object));

            var ExpressionLambda = Expression.Lambda<Func<TModel, object>>(returnObj, paramTmodel).Compile();

            return ExpressionLambda(model);
        }

        private static void SetValue<TModel>(this PropertyInfo p, TModel model, object value)
        {
            var instanceParam = Expression.Parameter(typeof(TModel), "instance");

            var valueParam = Expression.Parameter(typeof(object), "value");

            var ConvertValueParam = Expression.Convert(valueParam, value.GetType());

            var propertyProperty = Expression.Property(instanceParam, p);

            var assignExpression = Expression.Assign(propertyProperty, ConvertValueParam);

            var lambdaExpression = Expression.Lambda<Action<TModel, object>>(assignExpression, instanceParam, valueParam).Compile();

            lambdaExpression(model, value);
        }
        #endregion

        #region 序列化/反序列化
        private static string SerializeObject(object obj)
        {
            string result = string.Empty;
            using (MemoryStream stream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);

                byte[] byt = new byte[stream.Length];
                byt = stream.ToArray();
                result = Convert.ToBase64String(byt);
                stream.Flush();
            }
            return result;
        }

        private static object DeserializeObject(string str)
        {
            byte[] byt = Convert.FromBase64String(str);
            object obj = null;
            using (Stream stream = new MemoryStream(byt, 0, byt.Length))
            {
                IFormatter formatter = new BinaryFormatter();
                obj = formatter.Deserialize(stream);
            }
            return obj;
        }
        #endregion
        #endregion
    }

    #region Attribute
    /// <summary>
    /// 可序列化属性
    /// </summary>
    public class SerialAttribute : Attribute { }

    /// <summary>
    /// 非数据库字段属性
    /// </summary>
    public class NotDBFieldAttribute : Attribute { }
    #endregion

}

  

时间: 2024-11-03 21:06:42

自己写的.net ORM 框架的相关文章

自己写ORM框架 DBUtils

ORM框架想必大家都比较熟知了,即对象关系映射(英语:Object Relation Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换.从效果上说,它其实是创建了一个可在编程语言里使用的"虚拟对象数据库". 当你开发一个应用程序的时候(不使用O/R MAPPING),你可能会写不少数据访问层的代码,用来从数据库保存,删除,读取对象信息,等等. 现在流行的ORM框架有: JAVA系列:APACHE

自己写ORM框架 DBUtils_DG Java(C#的写在链接里)

ORM框架想必大家都比较熟知了,即对象关系映射(英语:Object Relation Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换.从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”. 当你开发一个应用程序的时候(不使用O/R MAPPING),你可能会写不少数据访问层的代码,用来从数据库保存,删除,读取对象信息,等等. 现在流行的ORM框架有: JAVA系列:APACHE OJB,C

手写MyBatis ORM框架实践

一.实现手写Mybatis三个难点 1.接口既然不能被实例化?那么我们是怎么实现能够调用的? 2.参数如何和sql绑定 3.返回结果 下面是Mybatis接口 二.Demo实现 1.创建Maven工程(开发工具Eclipse) 下一步 下一步 然后点击“完成” 2.配置pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema

尝试手写orm框架

前言: 在使用各种的orm框架的过程中,菜鸟的我始终没有搞懂底层实现技术,最近刚好没事找了些视频和资料了解一点皮毛,想记录下,大家勿喷. 所谓的ORM(Object Relational Mapping) 对象关系映射 官方解释是通过使用描述对象和数据库之间映射的元数据,将面向对象程序的对象自动持久化到关系数据库中. 个人理解就是一个数据库访问的帮助类,可以让我们不用手写sql,就完成数据库的访问 使用的技术: 泛型.反射.特性.扩展 摸索步骤: step1 新建项目,建几个类库,大家熟悉的三层

分享自己写的基于Dapper的轻量级ORM框架~

1.说明 本项目是一个使用.NET Standard 2.0开发的,基于 Dapper 的轻量级 ORM 框架,包含基本的CRUD以及根据表达式进行一些操作的方法,目前只针对单表,不包含多表连接操作. github:https://github.com/iamoldli/NetSql 2.使用方法 2.2.安装 Install-Package NetSql 2.2.创建实体 创建Article实体类,继承EntityBase public class Article : EntityBase {

ORM框架详解

.Net开源微型ORM框架测评 什么是ORM? 对象关系映射(英语:Object Relation Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换.从效果上说,它其实是创建了一个可在编程语言里使用的"虚拟对象数据库". 一般的ORM包括以下四部分: 一个对持久类对象进行CRUD操作的API: 一个语言或API用来规定与类和类属性相关的查询: 一个规定MAPPING METADATA的工具: 一种

轻量型ORM框架Dapper的使用

在真实的项目开发中,可能有些人比较喜欢写SQL语句,但是对于EF这种ORM框架比较排斥,那么轻量型的Dapper就是一个不错的选择,即让你写sql语句了,有进行了关系对象映射.其实对于EF吧,我说下我个人的见解,EF是相对来说比较重的ORM框架,它是讲究通用性的框架,而非单纯的实现某种需求的框架,不得不否认的说,EF的开发效率要比用单纯的ADO.NET写sql语句的效率高的不是一点半点,可能很多人会说EF的性能低等等,针对这种问题有时候是需要折中的来讲,从另一个方面来讲,你用了ADO.NET写s

GreenDao开源ORM框架浅析

Android程序开发中,避免不了要用到数据库,我们都知道android提供了内置的Sqlite,即调用SQLiteOpenHelper的方法,来操作数据库,但是使用过程较为繁琐,从建表到对表中数据的正删改查操作,需要大量的代码来建立表,和完成这些操作. GreenDao居然是ORM框架,它跟hibernate是很像的,就是当你配置了一些参数信息之后,可以由框架来帮你生成对应的实体类,还有生成对应的操作实体类的代码(自动建表和基本的增删改查). 优点: 1.最大性能(最快的Android ORM

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

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