根据sql语句和实体反射生成sqlparameter

 

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

namespace WisdomFish.Entity
{
    public static class DBExtend
    {
        public static List<SqlParameter> GetParameter<T>(string sql, T entity)
        {
            Regex regex = new Regex("@(?<pname>[^\\s*,)]*)");//查找@开头,空格,逗号,右括号结尾
            List<string> pStr = new List<string>();
            if (regex.IsMatch(sql))
            {
                MatchCollection collection = regex.Matches(sql);
                foreach (Match m in collection)
                {
                    pStr.Add(m.Groups["pname"].Value);//生成字段字符串
                }
            }
            Type t = typeof(T);
            PropertyInfo[] pinfo = t.GetProperties();//反射获取实体属性
            List<SqlParameter> pList = new List<SqlParameter>();
            foreach (var item in pStr)
            {
                for (int i = 0; i < pinfo.Length; i++)
                {
                    if (item.Equals(pinfo[i].Name, StringComparison.OrdinalIgnoreCase))
                    {
                        if (pinfo[i].GetValue(entity, null) == null)//如果为空
                        {
                            switch (pinfo[i].PropertyType.Name.ToLower())//判断字段类型
                            {
                                case"string":
                                    pList.Add(new SqlParameter { ParameterName = "@" + item, Value = "" });//空字符串,插入数据库就会保存,所以赋值""
                                    break;
                            }
                        }
                        else
                        {
                            pList.Add(new SqlParameter { ParameterName = "@" + item, Value = pinfo[i].GetValue(entity, null) });
                        }
                        
                        break;
                    }
                }
            }
            return pList;
        }
    }
}

 

posted @ 2016-11-28 10:46  wjl910  阅读(128)  评论(0)    收藏  举报