码迷,mamicode.com
首页 > 数据库 > 详细

利用反射将Model转化为sql

时间:2017-09-07 19:32:41      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:tsql   blog   foreach   color   col   span   type   UI   star   

 public string GetInsertSqlByModel(Object o)
        {
            StringBuilder sbStart = new StringBuilder();
            StringBuilder sbFields = new StringBuilder();
            StringBuilder sbValues = new StringBuilder();
            Type t = o.GetType();
            string modelName = t.Name;
            foreach (PropertyInfo p in t.GetProperties())
            {
                sbFields.Append(p.Name + ",");
                sbValues.AppendFormat("‘{0}‘,",p.GetValue(o));
            }
            sbStart.AppendFormat("insert into {0}({1}) values({2})",modelName,sbFields.ToString().TrimEnd(,), sbValues.ToString().TrimEnd(,));
            return sbStart.ToString();
        }

 

如果不需要添加为null或者为空的栏位,则可以使用如下代码 

      public string GetInsertSqlByModel(Object o)
        {
            StringBuilder sbStart = new StringBuilder();
            StringBuilder sbFields = new StringBuilder();
            StringBuilder sbValues = new StringBuilder();
            Type t = o.GetType();
            string modelName = t.Name;
            foreach (PropertyInfo p in t.GetProperties())
            {
                if (p.GetValue(o) == null||string.IsNullOrEmpty(p.GetValue(o).ToString()))
                {
                    continue;
                }
                sbFields.Append(p.Name + ",");
                sbValues.AppendFormat("‘{0}‘,",p.GetValue(o));
            }
            sbStart.AppendFormat("insert into {0}({1}) values({2})",modelName,sbFields.ToString().TrimEnd(,), sbValues.ToString().TrimEnd(,));
            return sbStart.ToString();
        }
    }

 

利用反射将Model转化为sql

标签:tsql   blog   foreach   color   col   span   type   UI   star   

原文地址:http://www.cnblogs.com/xuhongfei/p/7491108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!