用attribute实现ORM

来源:互联网 发布:莱阳螳螂拳淘宝 编辑:程序博客网 时间:2024/06/10 00:31

听说很多ORM框架都是用XML映属性和表字段的关系,现在看来用C#里的attribute好像也很方便。

namespace ConsoleApplication4
{
    class Class1
    {
       
        static void Main()
        {
            person p = new person();
            p.Name = "韩梅梅";
            p.Sex = "女";
            p.Age = 14;
            DBAccess dba = new DBAccess();
            dba.AddPerson(p);//
           
        }
    }
    [AttributeUsage(AttributeTargets.Property,AllowMultiple=true,Inherited=false)]
    public class DataFieldAttribute: Attribute
    {
        string _FieldName;
        string _FieldType;
        public DataFieldAttribute(string fieldName, string fieldType)
        {
            _FieldName = fieldName;
            _FieldType = fieldType;
        }
        public string FieldName
        {
            set { _FieldName =value; }
            get { return _FieldName; }
        }
        public string FiledType
        {
            set { _FieldType = value; }
            get { return _FieldType; }
        }
    }
    public class person
    {
        string _name;
        string _sex;
        int _age;
        [DataField("name","nvarchar")]
        public string Name
        {
            set { _name = value; }
            get { return _name; }
        }
        [DataField("sex","nvarchar")]
        public string Sex
        {
            set { _sex = value; }
            get { return _sex; }
        }
        [DataField("age","int")]
        public int Age
        {
            set { _age = value; }
            get { return _age; }
        }
    }
    public class DBAccess
    {      
        public void AddPerson(person p)
        {
            string[,] fieldPair = new string[3, 2];
            PropertyInfo[] arrPro = p.GetType().GetProperties();
            for (int i = 0; i < arrPro.Length;i++ )
            {

                object[] arrAttr = arrPro[i].GetCustomAttributes(typeof(DataFieldAttribute), false);
                string colName = ((DataFieldAttribute)arrAttr[0]).FieldName;//每个属性只有一个attribute
                string colValue = arrPro[i].GetValue(p, null).ToString();
                fieldPair[i, 0] = colName;
                fieldPair[i, 1] = colValue;

            }
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("INSERT INTO TablePerson({0},{1},{2})",fieldPair[0,0],fieldPair[1,0],fieldPair[2,0]);
            sb.AppendFormat(" VALUES('{0}','{1}',{2})", fieldPair[0, 1], fieldPair[1, 1], fieldPair[2, 1]);
            int l = fieldPair.Length;
            string strSql = sb.ToString();
            //执行sql语句;
        }
    }

原创粉丝点击