通用数据库访问类(泛型实现)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Configuration;
using System.Data.SqlClient;
using System.Reflection;
using System.Data;

namespace Test
{
    public class DataAccess
    {
        private static string conString;
        public DataAccess(string name)
        {
            //构造方法中读取并保存配置文件中的连接字符串
            if (string.IsNullOrEmpty(conString))
            {
                conString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
            }
        }

        //完成全部表的新增
        
//新增的sql语句是根据映射关系动态生成的
        
//T是实体类的类名
        public bool Add<T>(T obj) where T : new()
        {
            bool result = false;

            //动态构建sql语句和参数
            List<SqlParameter> pars = new List<SqlParameter>();
            StringBuilder sb = new StringBuilder();
            Type type = typeof(T);
            PropertyInfo[] pis = type.GetProperties();

            sb.Append("insert into " + type.Name + " values(");
            //按照属性循环,向SQL语句中添加参数,参数名=@属性名
            foreach (var pi in pis)
            {
                if (!(pi.Name.StartsWith("Id") || pi.Name.EndsWith("Id")))
                {
                    sb.Append("@" + pi.Name + ",");
                    //每个属性转换成参数对象
                    pars.Add(new SqlParameter("@" + pi.Name, pi.GetValue(obj)));
                }
                else
                {
                    if( Attribute.GetCustomAttribute(pi,typeof(FKAttribute))!=null)                    
                    {
                         sb.Append("@" + pi.Name + ",");
                         //每个属性转换成参数对象
                         pars.Add(new SqlParameter("@" + pi.Name, pi.GetValue(obj)));
              
                    }
                }
            }

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

            //访问数据库
            int rows = SqlHelper.ExecuteNonQuery(conString, CommandType.Text, sql, pars.ToArray());
            if (rows > 0) result = true;

            return result;
        }
    }
}

以上只实现了泛型的通用数据库新增功能,撸代码撸累了,剩下的功能改日再更新。

原文地址:https://www.cnblogs.com/turingchang/p/5287207.html