C# 用反射实现简单的ORM

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace 反射
{
    class ORMHelper<T>
    {
        string connStr;
        Type type;
        public ORMHelper(string constr)
        {
            connStr = constr;
            type = typeof(T);
        }

        public string GetTableName()
        {
            var attribute = type.GetCustomAttributes(typeof(KeyAttribute), false);
            return ((KeyAttribute)attribute[0]).TableName;
        }

        public string GetKeyName()
        {
            var attribute = type.GetCustomAttributes(typeof(KeyAttribute), false);
            return ((KeyAttribute)attribute[0]).PKName;
        }

        public void CreateTable()
        {
            StringBuilder sb = new StringBuilder();
            string tableName = GetTableName();
            string pk = GetKeyName();
            sb.Append(string.Format("if not exists (select * from sysobjects  where name='{0}' and xtype='U')", tableName));
            sb.Append(string.Format("Create Table {0}", tableName));
            sb.Append("(");

            //使用反射获取所有属性
            foreach (PropertyInfo p in type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                DataFiledAttribute colmn = p.GetCustomAttribute(typeof(DataFiledAttribute), false) as DataFiledAttribute;
                if (colmn.Name.ToUpper() == pk.ToUpper())
                {
                    sb.Append(string.Format("{0} {1} IDENTITY(1,1) NOT NULL PRIMARY KEY,", colmn.Name, colmn.Type));
                }
                else
                {
                    sb.Append(string.Format("{0} {1} NOT NULL,", colmn.Name, colmn.Type));
                }
            }

            var sql = sb.ToString().Substring(0, sb.Length - 1) + ")";
            ExcuteNonQuary(sql);
        }

        public void DropTable()
        {
            string sql = "Drop table " + GetTableName();
            ExcuteNonQuary(sql);
        }

        public bool HasExist(object id)
        {
            var tableName = GetTableName();
            var pk = GetKeyName();
            string sql = string.Format("select * from {0} where {1}={2}", tableName, pk, id);
            using (SqlConnection cn = new SqlConnection(connStr))
            {
                cn.Open();
                var cmd = new SqlCommand();
                cmd.CommandText = sql;
                cmd.Connection = cn;
                cmd.CommandType = CommandType.Text;
                return cmd.ExecuteReader().HasRows;
            }
        }


        public void Insert(object newObject)
        {
            var type = newObject.GetType();
            object newObjectValue = new object();
            var keyName = GetKeyName();
            var tableName = GetTableName();
            StringBuilder sb = new StringBuilder(200);
            sb.Append(string.Format("insert into {0} values(", tableName));
            foreach (var p in type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {

                if (p.Name.ToUpper() == keyName.ToUpper())
                {
                    continue;
                }
                else
                {
                    sb.Append("'");
                    sb.Append(p.GetValue(newObject).ToString());
                    sb.Append("',");
                }

            }

            var sql = sb.ToString().Substring(0, sb.Length - 1) + ")";
            ExcuteNonQuary(sql);
        }

        public int Count()
        {
            string pk = GetKeyName();
            string tableName = GetTableName();
            StringBuilder sb = new StringBuilder(50);
            sb.Append(string.Format("Select count({0}) from {1}", pk, tableName));
            using (SqlConnection cn = new SqlConnection(connStr))
            {
                cn.Open();
                SqlCommand command = new SqlCommand();
                command.CommandText = sb.ToString();
                command.Connection = cn;
                SqlDataReader reader = command.ExecuteReader();
                reader.Read();
                return reader.GetInt32(0);
            }

        }


        public T SelectById(int id)
        {

            string tableNam = GetTableName();
            string pk = GetKeyName();
            T obj = Activator.CreateInstance<T>();
            string sql = string.Format("Select * from {0} where {1}={2}", tableNam, pk, id);
            using (SqlConnection scn = new SqlConnection(connStr))
            {
                scn.Open();
                SqlCommand command = new SqlCommand();
                command.CommandText = sql;
                command.Connection = scn;
                var reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    int i = 0;
                    foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.PutDispProperty))
                    {

                        property.SetValue(obj, reader[i]);
                        i++;
                    }

                    return obj;
                }
                else
                {
                    return default(T);
                }
            }
        }

        private void ExcuteNonQuary(string sql)
        {

            using (SqlConnection cn = new SqlConnection(connStr))
            {
                cn.Open();
                SqlTransaction tans = cn.BeginTransaction();
                var cmd = new SqlCommand();
                cmd.CommandText = sql;
                cmd.Connection = cn;
                cmd.CommandType = CommandType.Text;
                cmd.Transaction = tans;
                cmd.ExecuteNonQuery();
                tans.Commit();
            }

        }
    }
}

测试代码:

  static void Main(string[] args)
        {
            ORMHelper<Person> orm = new ORMHelper<Person>(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ToString());
            orm.DropTable();
            orm.CreateTable();
            Person p = new Person();
            p.Name = "张三";
            p.Age = 12;
            p.Sex = "";
            orm.Insert(p);
            Person p1= orm.SelectById(1);
            Console.Write(p1.Name);
            Console.ReadKey();
        }

猜你喜欢

转载自www.cnblogs.com/ZHXI/p/12895155.html