全速加载中

利用反射将Model转化为sql

 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();
        }
    }

 

posted @ 2017-09-07 18:10  许鸿飞  阅读(265)  评论(0编辑  收藏  举报