zoukankan      html  css  js  c++  java
  • 手写ORM框架

        先准备Models中实体类

    ===================================================

       /// <summary>
        /// 用户信息
        /// </summary>
        [Serializable]
        public class Student_Info
        {
            [Identity]
            [PrimaryKey]
            public int ID { get; set; }
            public string Name { get; set; }
            public bool Sex { get; set; }
            public string ClassName { get; set; }
            public string BookName { get; set; }
            public DateTime BeginDateTime { get; set; }
            public DateTime EndDateTime { get; set; }

            [Peculiarity]
            public int ClassID { get; set; }

        }

    然后建立属性过滤的类:AttributeClass

    必须要用Attribute结尾,继承Attribute类

        /// <summary>
        /// 标识列属性
        /// </summary>
        public class IdentityAttribute:Attribute
        {
            public bool IsIdentity { get; } = true;
        }
        /// <summary>
        /// 主键属性
        /// </summary>
        public class PrimaryKeyAttribute : Attribute
        {
            public bool IsPrimaryKey { get; } = true;
        }
        /// <summary>
        /// 特性属性
        /// </summary>
        public class PeculiarityAttribute : Attribute
        {
            public bool IsPrimaryKey { get; } = true;
        }

    ===================================================

    准备DAL中的工作:

    建立一个文件夹:ORM.Core;

    建立一个DBContext的类;

    namespace DAL
    {
        /// <summary>
        /// ORM框架的核心操作(数据库上下文)
        /// </summary>
        public class DBContext
        {
            /// <summary>
            /// 添加
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="model"></param>
            /// <returns></returns>
            public int InsertModel<T>(T model) where T:class,new()
            {
                //1.获取当前实体类的所有属性(属性名称、类型、具体的属性值)
                PropertyInfo[] properites = model.GetType().GetProperties();

                //2.过滤掉不需要的属性
                List<string> columns = FilterColumnsByAttributes(properites, new string[] { "IdentityAttribute", "PeculiarityAttribute" });

                //3.准备
                StringBuilder sqlFields = new StringBuilder($"insert into {model.GetType().Name}(");
                StringBuilder sqlValues = new StringBuilder(" values(");
                List<SqlParameter> paramList = new List<SqlParameter>();
                //4.循环生成sql语句和参数封装
                foreach (PropertyInfo item in properites)
                {
                    //过滤不需要的字段
                    if (columns.Contains(item.Name)) continue;
                    //过滤属性值为null的
                    if (item.GetValue(model) == null) continue;
                    //时间属性过滤
                   
                    sqlFields.Append($"{item.Name},");
                    sqlValues.Append($"@{item.Name},"); //values值是参数,必须加@符号进行参数化防注入
                    paramList.Add(new SqlParameter($"@{item.Name}", item.GetValue(model)));
                }

                string sql1 = sqlFields.ToString().TrimEnd(',') + ")";
                string sql2 = sqlValues.ToString().TrimEnd(',') + ")";
                string sql = sql1 + sql2;
                //5.调用SQLHelper通用类完成数据库操作
                return SQLHelper.ExecuteNonQuery(sql, paramList.ToArray());
            }

            /// <summary>
            /// 过滤不需要的属性
            /// </summary>
            /// <param name="properites"></param>
            /// <param name="attrNames"></param>
            /// <returns></returns>
            private List<string> FilterColumnsByAttributes(PropertyInfo[] properites,string[] attrNames)
            {
                List<string> columns = new List<string>();
                foreach (string attrName in attrNames)
                {
                    foreach (PropertyInfo item in properites)
                    {
                        object[] cusAttrbutes = item.GetCustomAttributes(true);//找到当前属性的所有自定义特性
                        foreach (var attribute in cusAttrbutes)
                        {
                            if(attribute.GetType().Name.Equals(attrName))
                            {
                                columns.Add(item.Name);
                                break;
                            }
                        }
                    }
                }
                return columns;
            }
            
        }
    }

    附上SQLHelper类;

    public class SQLHelper
        {
            //定义一个私有的、只读的、静态的变量(获取config文件中的数据库连接)
            private readonly static string str = ConfigurationManager.ConnectionStrings["myweb"].ConnectionString;

            /// <summary>
            /// 执行方法ExecuteScalar,返回查询到的首行首列
            /// </summary>
            /// <param name="sql"></param>
            /// <param name="pams"></param>
            /// <returns></returns>
            public static object ExecuteScalar(string sql, params SqlParameter[] pams)
            {

                using (SqlConnection con = new SqlConnection(str))
                {
                    using (SqlCommand com = new SqlCommand(sql, con))
                    {
                        if (pams != null && pams.Length > 0)
                        {
                            com.Parameters.AddRange(pams);
                        }
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        return com.ExecuteScalar();
                    }
                }
            }

            /// <summary>
            /// 执行方法ExecuteNonQuery,返回受影响的行数
            /// </summary>
            /// <param name="sql"></param>
            /// <param name="pams"></param>
            /// <returns></returns>
            public static int ExecuteNonQuery(string sql, params SqlParameter[] pams)
            {

                using (SqlConnection con = new SqlConnection(str))
                {
                    using (SqlCommand com = new SqlCommand(sql, con))
                    {
                        if (pams != null && pams.Length > 0)
                        {
                            com.Parameters.AddRange(pams);
                        }
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        return com.ExecuteNonQuery();
                    }
                }
            }

            /// <summary>
            /// 执行方法ExecuteReader,返回SqlDataReader读取的数据
            /// </summary>
            /// <param name="sql"></param>
            /// <param name="pams"></param>
            /// <returns></returns>
            public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pams)
            {
                SqlConnection con = new SqlConnection(str);
                using (SqlCommand com = new SqlCommand(sql, con))
                {
                    if (pams != null && pams.Length > 0)
                    {
                        com.Parameters.AddRange(pams);
                    }
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    return com.ExecuteReader();
                }

            }

            /// <summary>
            /// 执行ExecuteDataTable方法,返回DataTable
            /// </summary>
            /// <param name="sql"></param>
            /// <param name="pams"></param>
            /// <returns></returns>
            public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pams)
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(sql, str))
                {
                    if (pams != null)
                    {
                        sda.SelectCommand.Parameters.AddRange(pams);
                    }
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
            /// <summary>
            /// 用存储过程执行方法ExecuteReaderProc,返回SqlDataReader读取的数据
            /// </summary>
            /// <param name="sql"></param>
            /// <param name="pams"></param>
            /// <returns></returns>
            public static SqlDataReader ExecuteReaderProc(string sql, params SqlParameter[] pams)
            {

                SqlConnection con = new SqlConnection(str);
                using (SqlCommand com = new SqlCommand(sql, con))
                {
                    com.CommandType = CommandType.StoredProcedure;
                    if (pams != null && pams.Length > 0)
                    {
                        com.Parameters.AddRange(pams);
                    }
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    return com.ExecuteReader();
                }

            }
            /// <summary>
            /// 使用存储过程执行方法ExecuteNonQueryPrco,返回受影响的行数
            /// </summary>
            /// <param name="sql"></param>
            /// <param name="pams"></param>
            /// <returns></returns>
            public static int ExecuteNonQueryPrco(string sql, params SqlParameter[] pams)
            {

                using (SqlConnection con = new SqlConnection(str))
                {
                    using (SqlCommand com = new SqlCommand(sql, con))
                    {
                        com.CommandType = CommandType.StoredProcedure;
                        if (pams != null && pams.Length > 0)
                        {
                            com.Parameters.AddRange(pams);
                        }
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        return com.ExecuteNonQuery();
                    }
                }
            }
        }

    ===================================================

    DAL中的Service类;

    namespace DAL
    {

       //定义一个泛型,条件:必须是引用类型,无参
        public class Service<T> where T:class,new()
        {
            /// <summary>
            /// 添加实体方法
            /// </summary>
            /// <param name="entity"></param>
            /// <returns></returns>
            public int Add(T entity)
            {
                DBContext db = new DBContext();
                return db.InsertModel(entity);           
            }
        }
    }

    ===================================================

    BLL中写为泛型;

       public class Manager<T> where T : class, new()
        {
            Service<T> a = new Service<T>();

            /// <summary>
            /// BLL中的添加数据
            /// </summary>
            /// <param name="student"></param>
            /// <returns></returns>
            public int Insert(T entity)
            {
                return a.Add(entity);
            }
        }

    ===================================================

    前台代码调用;

    Manager<Student_Info> BLL_MG = new Manager<Student_Info>();      

    Student_Info info = new Student_Info();     

    info.ID = 14;      

    info.Name = "王五";       

    info.Sex = true;        

    info.ClassName = "王五";       

    info.BookName = "C#从入门到精通";    

    info.BeginDateTime = DateTime.Parse(DateTime.Parse("2019-01-01").ToString("yyyy-MM-dd HH:mm:ss"));        

    info.EndDateTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

    BLL_MG.Insert(info);

    ===================================================

  • 相关阅读:
    Android平台下基于XMPP的IM研究
    Android File数据存储
    Android 获取屏幕分辨率的方式
    Android TabHost 动态修改图标或者动态改变标题
    Android DatePickerDialog用法
    SharedPreference Demo
    progressdialog 去边框
    [LCT学习时的一些笔记]
    [ZJOI2007]最大半连通子图
    【Matrixtree Theorem学习笔记】
  • 原文地址:https://www.cnblogs.com/result-xiaoqiang/p/10735644.html
Copyright © 2011-2022 走看看