zoukankan      html  css  js  c++  java
  • .NET ORM框架(一)

    最近做项目自己整理了一个ORM框架,分享给大家看看,有很多不足望大家指出。

    下面是使用方法

    BLL 主要方法

    逻辑层:子类继承父类, 直接用BASE调用 ManagerBLL 中的方法。

     public class TestBLL : ManagerBLL
        {
            public static TestBLL __instance = null;
            //原先有打算采用单列模式,结果悲剧啦!,后面只有整体修改下面这个方法。
            public static TestBLL GetInstance()
            {
                if (__instance == null) __instance = new TestBLL();
                return new TestBLL();
            }
    
            public void test() 
            {
                Admin_User admin=new Admin_User();
                admin.User_Name="";
                admin.User_NikeName="";         
                //条件
                WhereClip<Admin_User> where = new WhereClip<Admin_User>(a => a.User_Name=="x" && a.User_ID == 1 || a.User_RegIP=="dd");
                where.And(a=>a.User_Status==1);
                where.Or(a=>a.User_TrueName=="");
                //模糊条件
                where.And(a=>a.User_Password.Like(String.Format("%{0}%",1)));
                //列名
                ColumnsClip<Admin_User> columnsClip=new ColumnsClip<Admin_User>(a=>a.Columns(a.User_ID,a.User_LastIP,a.User_LoginNumber));
                //排序
                OrderByClip<Admin_User> orderByClip=new OrderByClip<Admin_User>(a=>a.OrderBy(a.User_ID.Desc(),a.User_LastIP.Asc()));
                //查询第一行第一列
                base.GetCount(where);
                //查询一行
                base.Get(columnsClip, where, orderByClip);
                //查询成List
                base.GetList(0, columnsClip, where, orderByClip);
                //分页查询
                base.GetList(columnsClip, where, orderByClip, 10, 1, 0);
                //添加
                base.Add(admin);
                //批量添加-事物
                List<BaseEntity> list = new List<BaseEntity>();
                Admin_User admins = (Admin_User)admin.Clone();//深度复制
                list.Add(admin);
                list.Add(admins);
                base.AddList(list);
                //修改
                base.Edit(admin, where);
                //批量修改-事物
                Dictionary<BaseEntity, object> dic = new Dictionary<BaseEntity, object>();
                dic.Add(admin, where);
                dic.Add(admins, where);
                base.EditList(dic);
                //删除
                base.Remove(admin);
                //批量删除-事物
                base.RemoveList(dic);
            }
        }
    

    实体类:codesmith 脚本写好既可以自动生成实体,非常方便快捷。

     /// <summary>
        /// Modal class: Admin_User.
        /// </summary>
        [Serializable]
        [Table(Name = "Admin_User", PrimaryKey = "user_ID")]
        public class Admin_User : BaseEntity
        {
            #region Private Properties
    
            private int? user_ID;//ID
            private string user_Name;//用户名
            private string user_Password;//密码
            private string user_NikeName;//用户昵称
            private string user_TrueName;//用户真实姓名
            private string user_Email;//Email
            private string user_RegIP;//注册IP
            private DateTime? user_CreateTime;//注册时间
            private int? user_LoginNumber;//登录次数
            private DateTime? user_LastTime;//最后登录时间
            private string user_LastIP;//最后登录IP
            private int? user_Status;//状态
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// ID.
            /// </summary>
            [Column(Name = "user_ID", PrimaryKey = true, Strategy = GenerationType.INDENTITY)]
            public int? User_ID
            {
                get
                {
                    return user_ID;
                }
                set
                {
    
                    user_ID = value;
                }
            }
    
            /// <summary>
            /// 用户名.
            /// </summary>
            [Column(Name = "user_Name")]
            public string User_Name
            {
                get
                {
                    return user_Name;
                }
                set
                {
                    user_Name = value.SubStr(50);
                }
            }
    
    
            /// <summary>
            /// 密码.
            /// </summary>
            [Column(Name = "user_Password")]
            public string User_Password
            {
                get
                {
                    return user_Password;
                }
                set
                {
                    user_Password = value.SubStr(50);
                }
            }
    
    
            /// <summary>
            /// 用户昵称.
            /// </summary>
            [Column(Name = "user_NikeName")]
            public string User_NikeName
            {
                get
                {
                    return user_NikeName;
                }
                set
                {
                    user_NikeName = value.SubStr(50);
                }
            }
    
    
            /// <summary>
            /// 用户真实姓名.
            /// </summary>
            [Column(Name = "user_TrueName")]
            public string User_TrueName
            {
                get
                {
                    return user_TrueName;
                }
                set
                {
                    user_TrueName = value.SubStr(50);
                }
            }
    
    
            /// <summary>
            /// Email.
            /// </summary>
            [Column(Name = "user_Email")]
            public string User_Email
            {
                get
                {
                    return user_Email;
                }
                set
                {
                    user_Email = value.SubStr(50);
                }
            }
    
    
            /// <summary>
            /// 注册IP.
            /// </summary>
            [Column(Name = "user_RegIP")]
            public string User_RegIP
            {
                get
                {
                    return user_RegIP;
                }
                set
                {
                    user_RegIP = value.SubStr(50);
                }
            }
    
    
            /// <summary>
            /// 注册时间.
            /// </summary>
            [Column(Name = "user_CreateTime")]
            public DateTime? User_CreateTime
            {
                get
                {
                    return user_CreateTime;
                }
                set
                {
                    user_CreateTime = value;
                }
            }
    
    
            /// <summary>
            /// 登录次数.
            /// </summary>
            [Column(Name = "user_LoginNumber")]
            public int? User_LoginNumber
            {
                get
                {
                    return user_LoginNumber;
                }
                set
                {
                    user_LoginNumber = value;
                }
            }
    
    
            /// <summary>
            /// 最后登录时间.
            /// </summary>
            [Column(Name = "user_LastTime")]
            public DateTime? User_LastTime
            {
                get
                {
                    return user_LastTime;
                }
                set
                {
                    user_LastTime = value;
                }
            }
    
    
            /// <summary>
            /// 最后登录IP.
            /// </summary>
            [Column(Name = "user_LastIP")]
            public string User_LastIP
            {
                get
                {
                    return user_LastIP;
                }
                set
                {
                    user_LastIP = value.SubStr(50);
                }
            }
    
    
            /// <summary>
            /// 状态.
            /// </summary>
            [Column(Name = "user_Status")]
            public int? User_Status
            {
                get
                {
                    return user_Status;
                }
                set
                {
                    user_Status = value;
                }
            }
    
    
    
            #endregion
    
    
        }
    

     EntityManager 接口

    public interface EntityManager
        {
    
            T Get<T>(WhereClip<T> whereClip) where T : BaseEntity, new();
    
            T Get<T>(ColumnsClip<T> columnsClip, WhereClip<T> whereClip, OrderByClip<T> orderByClip) where T : BaseEntity, new();
    
            List<T> GetList<T>(int top, ColumnsClip<T> columnsClip, WhereClip<T> whereClip, OrderByClip<T> orderByClip) where T : BaseEntity, new();
    
            int GetCount<T>(WhereClip<T> whereClip) where T : BaseEntity, new();
    
            //分页查询
            ConditionResult<T> GetList<T>(ColumnsClip<T> columnsClip, WhereClip<T> whereClip, OrderByClip<T> orderByClip, int nPageSize, int nPageIndex, int nTotalCount) where T : BaseEntity, new();
    
            //新增
            int Add<T>(T entity);
    
            //批量新增,采用事务
            bool AddList<T>(List<T> entityList);
    
            //修改
            int Edit<T>(T entity);
    
            //多条件修改
            int Edit<T>(T entity, WhereClip<T> whereClip) where T : BaseEntity, new();
    
            //批量修改,采用事物
            bool EditList<T>(Dictionary<T, object> dicList) where T : BaseEntity, new();
    
            //删除
            int Remove<T>(T entity);
    
            //根据ID删除数据
            int Remove<T>(WhereClip<T> whereClip) where T : BaseEntity, new();
    
            //批量删除,采用事物
            bool RemoveList<T>(Dictionary<T, object> dicList) where T : BaseEntity, new();
        }
    

      ManagerBLL 核心

            /// <summary>
            /// 获取一行数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="whereClip"></param>
            /// <returns></returns>
            /// 
            public T Get<T>(WhereClip<T> whereClip) where T : BaseEntity, new()
            {
                //说明 性能问题还尚未考虑。
                T _T = new T();
    
                PropertyInfo[] properties = ReflectionUtils.GetProperties(_T.GetType());
    
                string whereString = string.Empty;
    
                if (whereClip != null)
                    whereString = whereClip.WhereString;
    
                TableInfo tableInfo = DbEntityUtils.GetTableInfo(_T, DbOperateType.SELECT);
    
                string commandText = BuildSql.GetFristSql(0, tableInfo, whereString, string.Empty);
    
                IDataReader sdr = null;
                if (whereClip != null)
                {
                    DbParameter[] parms = SqlOpera.MakeInParams(whereClip.Table);
                    sdr = SqlOpera.ExecuteReader(CommandType.Text, commandText, parms);
                }
                else
                    sdr = SqlOpera.ExecuteReader(CommandType.Text, commandText);
    
                while (sdr.Read())
                {
                    foreach (PropertyInfo property in properties)
                    {
                        //通过实体类属性名称获取Column自定义属性配置的映射列名
                        string name = tableInfo.PropToColumn[property.Name].ToString();
    
    
                        //通过获取的列名从dataReader中检索值,并赋给实体对象属性
                        ReflectionUtils.SetPropertyValue(_T, property, sdr[name]);
                    }
                    break;
                }
                sdr.Close();
                return _T;
            }
    
            /// <summary>
            /// 获取一行数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="columnsClip"></param>
            /// <param name="whereClip"></param>
            /// <param name="orderByClip"></param>
            /// <returns></returns>
            public T Get<T>(ColumnsClip<T> columnsClip, WhereClip<T> whereClip, OrderByClip<T> orderByClip) where T : BaseEntity, new()
            {
                //说明 性能问题还尚未考虑。
                T _T = new T();
                string orderByWhere = string.Empty;
                string columnsWhere = string.Empty;
                string whereString = string.Empty;
                PropertyInfo[] properties = ReflectionUtils.GetProperties(_T.GetType());
    
                if (orderByClip != null)
                    orderByWhere = orderByClip.OrderByWhere;
    
                if (columnsClip != null)
                    columnsWhere = columnsClip.ColumnsWhere;
    
                if (whereClip != null)
                    whereString = whereClip.WhereString;
    
    
                TableInfo tableInfo = null;
                if (columnsClip == null)
                    tableInfo = DbEntityUtils.GetTableInfo(_T, DbOperateType.SELECT);
    
                string tableName = DbEntityUtils.GetTableName(_T.GetType());//获取表名
    
                string commandText = null;
    
                if (columnsClip != null)
                    commandText = BuildSql.GetFristSqlByWhere(tableName, columnsWhere, whereString, orderByWhere);
                else
                    commandText = BuildSql.GetFristSql(0, tableInfo, whereString, orderByWhere);
    
                IDataReader sdr = null;
                if (whereClip != null)
                {
                    DbParameter[] parms = SqlOpera.MakeInParams(whereClip.Table);
                    sdr = SqlOpera.ExecuteReader(CommandType.Text, commandText, parms);
                }
                else
                {
                    sdr = SqlOpera.ExecuteReader(CommandType.Text, commandText);
                }
    
                while (sdr.Read())
                {
                    foreach (PropertyInfo property in properties)
                    {
                        //通过实体类属性名称获取Column自定义属性配置的映射列名
                        string name = DbEntityUtils.GetColumnAttributeName(property);
    
                        //通过获取的列名从dataReader中检索值,并赋给实体对象属性
                        for (int i = 0; i < sdr.FieldCount; i++)
                        {
                            if (sdr.GetName(i) == name)
                            {
                                ReflectionUtils.SetPropertyValue(_T, property, sdr[name]);
                                break;
                            }
                        }
                    }
                    break;
                }
                sdr.Close();
                return _T;
            }
    
            /// <summary>
            /// 获取List集合
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="top"></param>
            /// <param name="columnsClip"></param>
            /// <param name="whereClip"></param>
            /// <param name="orderByClip"></param>
            /// <returns></returns>
            public List<T> GetList<T>(int top, ColumnsClip<T> columnsClip, WhereClip<T> whereClip, OrderByClip<T> orderByClip) where T : BaseEntity, new()
            {
    
                //说明 性能问题还尚未考虑。
                T _T = new T();
                List<T> listT = new List<T>();
                string orderByWhere = string.Empty;
                string columnsWhere = string.Empty;
                string whereString = string.Empty;
                PropertyInfo[] properties = ReflectionUtils.GetProperties(_T.GetType());
    
                if (orderByClip != null)
                    orderByWhere = orderByClip.OrderByWhere;
    
                if (columnsClip != null)
                    columnsWhere = columnsClip.ColumnsWhere;
    
                if (whereClip != null)
                    whereString = whereClip.WhereString;
    
                string commandText = null;
                DataSet ds = null;
    
                if (columnsClip != null)
                {
                    string tableName = DbEntityUtils.GetTableName(_T.GetType());//获取表名
                    commandText = BuildSql.GetListSql(top, tableName, columnsWhere, whereString, orderByWhere);
                }
                else
                {
                    TableInfo tableInfo = DbEntityUtils.GetTableInfo(_T, DbOperateType.SELECT);
                    commandText = BuildSql.GetFristSql(top, tableInfo, whereString, orderByWhere);
                }
    
                if (whereClip != null)
                {
                    DbParameter[] parms = SqlOpera.MakeInParams(whereClip.Table);
                    ds = SqlOpera.ExecuteDataset(CommandType.Text, commandText, parms);
                }
                else
                {
                    ds = SqlOpera.ExecuteDataset(CommandType.Text, commandText);
                }
    
                if (ds.Tables.Count == 0) return listT;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    T entityT = new T();
                    foreach (PropertyInfo property in properties)
                    {
                        //通过实体类属性名称获取Column自定义属性配置的映射列名
                        string name = DbEntityUtils.GetColumnAttributeName(property);
    
                        //通过获取的列名从datatable中检索值,并赋给实体对象属性
    
                        if (dr.Table.Columns.Contains(name))
                            ReflectionUtils.SetPropertyValue(entityT, property, dr[name]);
    
                    }
                    listT.Add(entityT);
                }
    
    
                return listT;
            }
    
            /// <summary>
            /// 分页
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="columnsClip"></param>
            /// <param name="whereClip"></param>
            /// <param name="orderByClip"></param>
            /// <param name="nPageSize"></param>
            /// <param name="nPageIndex"></param>
            /// <param name="nTotalCount"></param>
            /// <returns></returns>
            public ConditionResult<T> GetList<T>(ColumnsClip<T> columnsClip, WhereClip<T> whereClip, OrderByClip<T> orderByClip, int nPageSize, int nPageIndex, int nTotalCount) where T : BaseEntity, new()
            {
    
                T _T = new T();
                List<T> listT = new List<T>();
                ConditionResult<T> conditionResult = new ConditionResult<T>();
                string orderByWhere = string.Empty;
                string columnsWhere = string.Empty;
                string whereString = string.Empty;
                int totalCount = 0;
                PropertyInfo[] properties = ReflectionUtils.GetProperties(_T.GetType());
    
                if (orderByClip != null)
                    orderByWhere = orderByClip.OrderByWhere;
    
                if (columnsClip != null)
                    columnsWhere = columnsClip.ColumnsWhere;
    
                if (whereClip != null)
                    whereString = whereClip.WhereString;
    
                totalCount = GetCount(whereClip);
    
                string commandText = null;
    
                DataSet ds = null;
    
                TableInfo tableInfo = DbEntityUtils.GetTableInfo(_T, DbOperateType.SELECT);
                string tableName = DbEntityUtils.GetTableName(_T.GetType());//获取表名
                commandText = BuildSql.GetPageSql(tableName, columnsWhere, whereString, orderByWhere, nPageSize, nPageIndex, tableInfo);
    
                if (whereClip != null)
                {
                    DbParameter[] parms = SqlOpera.MakeInParams(whereClip.Table);
                    ds = SqlOpera.ExecuteDataset(CommandType.Text, commandText, parms);
                }
                else
                {
                    ds = SqlOpera.ExecuteDataset(CommandType.Text, commandText);
                }
    
                if (ds.Tables.Count == 0) return conditionResult;
    
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    T entityT = new T();
                    foreach (PropertyInfo property in properties)
                    {
                        //通过实体类属性名称获取Column自定义属性配置的映射列名
                        string name = DbEntityUtils.GetColumnAttributeName(property);
    
                        //通过获取的列名从datatable中检索值,并赋给实体对象属性
    
                        if (dr.Table.Columns.Contains(name))
                            ReflectionUtils.SetPropertyValue(entityT, property, dr[name]);
    
                    }
                    listT.Add(entityT);
                }
    
                conditionResult.ResultList = listT;
                conditionResult.PageSize = nPageSize;
                conditionResult.TotalCount = totalCount;
                conditionResult.TotalPage = (int)Math.Ceiling((double)totalCount / nPageSize);
                conditionResult.PageIndex = nPageIndex;
                return conditionResult;
            }
    
            /// <summary>
            /// 获取第一行第一列
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="whereClip"></param>
            /// <returns></returns>
            public int GetCount<T>(WhereClip<T> whereClip) where T : BaseEntity, new()
            {
                Type type = new T().GetType();
    
                string whereString = string.Empty;
    
                if (whereClip != null)
                    whereString = whereClip.WhereString;
    
                string tableName = DbEntityUtils.GetTableName(type);//获取表名
    
                string commandText = BuildSql.GetCountSql(tableName, whereString);
    
                ////执行SQL命令  
                object val = null;
                if (whereClip != null)
                {
                    DbParameter[] parms = SqlOpera.MakeInParams(whereClip.Table);
                    val = SqlOpera.ExecuteScalar(CommandType.Text, commandText, parms);
                }
                else
                    val = SqlOpera.ExecuteScalar(CommandType.Text, commandText);
    
                //返回所影响的行数
                return Utils.StrToInt(val, 0);
            }

    ManagerBLL 必须实现 EntityManager 接口,部分代码还未贴。

    ------------------------------------------------------------------

    整理中。。。。。

  • 相关阅读:
    运行ConnectionDemo时遇到的问题及解决方案
    xampp启动MySQL出现Error: MySQL shutdown unexpectedly.
    20175227张雪莹 2018-2019-2 《Java程序设计》第八周学习总结
    KMS
    MAC 添加共享,脚本执行
    zabbix企业应用之windows系统安装omsa硬件监控
    SCCM大致安装过程,参考前辈教程完成部署
    MAC加域重复跳出---"talagent"想使用“本地项目” 的钥匙串
    CentOS Linux解决 Device eth0 does not seem to be present
    zabbix3.0.4 部署History
  • 原文地址:https://www.cnblogs.com/ysq5202121/p/3418032.html
Copyright © 2011-2022 走看看