定义通用访问数据库类

     最近在公司看封装的代码,访问数据库很方便,我们只需定义Model,便可访问数据库,当然了都是封装的dll,因此自己也试着写了一个,现在做个记录。

下面是特性标签的定义,主要用于获取本地属性定义和数据库定义以及数据库字段定义:

 public class DataMappingAttribute : Attribute
    {
        private string localName, dbName;
        private string type;
        public DataMappingAttribute(string a, string b, DbType type)
        {
            this.localName = a;
            this.dbName = b;
            this.type = "System." + type.ToString();
        }

        public string LocalName
        {
            get { return localName; }
        }
        public string DbName { get { return dbName; } }
        public string DataType { get { return type; } }
    }

 下面是数据库访问后,生成实体模型数据列表,主要用到泛型,反射技术,先生成Datatable定义,然后用数据库数据填充,遍历每一个行数据,根据自定义属性,确定数据和对象是如何一一对应的:

public class DataCommand
    {
        private const string ConnStr = "Data Source=.;Initial Catalog=xxx;User Id=sa;Password=xxx;";
        public List<T> Exe<T>(string cmdStr)
        {
            var resList = new List<T>();

            var dt = new DataTable();
            /*数据库字段与Datatable绑定*/
            var type = typeof(T);
            var fieldList = type.GetProperties();
            foreach (var filed in fieldList)
            {
                var attributes = filed.GetCustomAttributes(typeof(DataMappingAttribute), false);
                var ab = (DataMappingAttribute)attributes[0];
                dt.Columns.Add(ab.DbName,Type.GetType(ab.DataType));
            }
            
            using (var connection = new SqlConnection(ConnStr))
            {
                connection.Open();
                var cmd = new SqlCommand {Connection = connection};
                cmd.CommandText = cmdStr;
                var dataAdapter = new SqlDataAdapter(cmd);
                dataAdapter.Fill(dt);
                connection.Close();
            }

            foreach (DataRow row in dt.Rows)
            {
                var objT = Activator.CreateInstance<T>();
                foreach (var filed in fieldList)
                {
                    var attributes = filed.GetCustomAttributes(typeof(DataMappingAttribute), false);
                    var tempName = "";
                    foreach (var attr in attributes)
                    {
                        var attri = (DataMappingAttribute)attr;
                        if (attri.LocalName.Equals(filed.Name))
                            tempName = attri.DbName;
                    }
                   
                    if (!filed.CanWrite ||string.IsNullOrWhiteSpace(tempName)) continue;
                    filed.SetValue(objT,row[tempName], null);
                }
                resList.Add(objT);
            }
            return resList;
        }

 

posted on 2014-12-22 00:02  益而不损  阅读(286)  评论(0编辑  收藏  举报