C#通过反射写ORM的添加

写ORM有四个步骤

1.获取对象的属性数组

2.去除标识列

3.去除数据表的非映射字段

4.写sql语句

using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Reflection;//引用反射的命名空间
using System.Text;

namespace DAL
{
    public class DALORM
    {
        public static int SaveBySql(object model)
        {
            //1.获取实体对象的属性数组
            PropertyInfo[] proArray = model.GetType().GetProperties();
            //2.获取标识列
            string identity = GetIdentity(proArray);
            //3.获取所有非对映数据表字段的属性(扩展属性)
            List<string> NonPropertyList=GetNonFieldProperty(proArray);
            //4.组合sql语句
            StringBuilder sqlFiled = new StringBuilder("insert into "+model.GetType().Name+"(");
            StringBuilder sqlValues = new StringBuilder(" values(");
            foreach (PropertyInfo item in proArray)
            {
                //过滤标识列和非映射属性
                if (item.Name == identity) continue;
                if (NonPropertyList.Contains(item.Name)) continue;
                string columnValue = item.GetValue(model, null)+"";//获取属性值
                if (columnValue == null) continue;//如果属性值为null,我们一般不需要这个字段
                Type fieldType = item.PropertyType;//获取属性的类型
                if (fieldType == typeof(DateTime))
                {
                    DateTime dt;
                    DateTime.TryParse(columnValue, out dt);//将日期时间字符串转换成标准的日期和时间格式
                    if (dt <= SqlDateTime.MinValue.Value)//如果时间是最小值,则认为用户没有封装日期时间属性
                        continue;
                 }
                sqlFiled.Append(item.Name + ",");//在sql语句中添加一个字段名
                if (fieldType == typeof(string) || fieldType == typeof(DateTime))
                {
                    sqlValues.Append("'" + columnValue + "',"); //在sql与剧中添加values的执行,字符串类型的必须要添加字符串
                }
                else
                {
                    sqlValues.Append(columnValue + ",");
                }
                

            }
            //整合字段部分
            string start = sqlFiled.ToString();
            start = start.Substring(0, start.Length - 1) + ")";//去掉最后一个逗号,添加半个括号
            //整合值部分
            string end = sqlValues.ToString();
            end = end.Substring(0, end.Length - 1) + ")";
            //完整的sql语句
            string sqlText = start + end;
            //调用普通的通用数据访问类
            return DBHelper.ExecuteNonQuery(sqlText);
        }
        /// <summary>
        /// 获取标识列属性
        /// </summary>
        /// <param name="propinfo"></param>
        /// <returns></returns>
        public static string GetIdentity(PropertyInfo[] propinfo)
        {
            string identity = string.Empty;
            foreach (PropertyInfo item in propinfo)
            {
                //返回自定义数组的所有的特性
                object[] attrs = item.GetCustomAttributes(false);
                foreach (var id in attrs)
                {
                    if (id.GetType().Name == "IdentityAttribute")
                    {
                        identity = item.Name;
                        break;
                    }
                }
            }
            return identity;
        }
        /// <summary>
        /// 获取所有非数据库表字段映射属性
        /// </summary>
        /// <param name="propinfo"></param>
        /// <returns></returns>
        public static List<string> GetNonFieldProperty(PropertyInfo[] propinfo)
        {
            List<string> list = new List<string>();
            foreach (PropertyInfo item in propinfo)
            {
                object[] attrs = item.GetCustomAttributes(false);
                foreach (var id in attrs)
                {
                    if(id.GetType().Name== "NonTableAttribute")
                    {
                        list.Add(item.Name);
                        break;
                    }
                }
            }
            return list;
        }
       
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Models
{
    [AttributeUsage(AttributeTargets.Property)]
    public class PrimaryKeyAttribute : Attribute
    {
        public PrimaryKeyAttribute(bool primaryKey)
        {
            this.Value = primaryKey;
        }
        public bool Value { get; protected set; }
        public bool autoIncrement = false;
    }
    [AttributeUsage(AttributeTargets.Property)]
    public class NonTableAttribute : Attribute
    {
        public NonTableAttribute(bool primaryKey)
        {
            this.Value = primaryKey;
        }
        public bool Value { get; protected set; }
        public bool autoIncrement = false;
    }
    [AttributeUsage(AttributeTargets.Property)]
    public class IdentityAttribute : Attribute
    {
        public bool IsIdentity { get; set; }
    }
    /// <summary>
    /// 学员实体类
    /// </summary>
    /// 标记为可序列化
    [Serializable]
    public  class Students
    {
        //设置为标识列
        [Identity(IsIdentity=true)]
        //主键属性
        [PrimaryKeyAttribute(true)]
        public int StudentId { get; set; }
        #region 普通属性
        private string studentName;
        public string StudentName
        {
            get { return studentName; }
            set { studentName = value; }
        }
        private string gender;
        public string Gender
        {
            get { return gender; }
            set { gender = value; }
        }
        private DateTime birthiday;
        public DateTime Birthday
        {
            get { return birthiday; }
            set { birthiday = value; }
        }

        #endregion
        //扩展属性
        [NonTableAttribute(true)]//非映射的属性,扩展属性
        public string ClassName { get; set; }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值