将List转化成 DataTable--调整可空类型的转化错误

加载表结构并保持成XML

string cmdText = @"select   * from kb_lable_temp where 1=2";

                using (SqlConnection conn = new SqlConnection(DBCtx.ConnStr))

                {

                      DataTable dt = new DataTable();

                      SqlCommand cmd = new SqlCommand(cmdText,conn);

                      conn.Open();

                      using (var dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly))

                      {

                          dt.Load(dr);

                          dt.WriteXmlSchema("C:\\xxx.xml");

                      }

                      



                }

                DataTable dt3 = new DataTable();

                dt3.ReadXmlSchema("C:\\xxx.xml");

List<T>到DataTable

using System.Data;

using System.Collections.Generic;

using System.Reflection;

using System;

using System.Collections;

namespace F.Studio.Util

{

    public static class DataTableExtensions

    {

        /// <summary> 

        /// 转化一个DataTable 

        /// </summary> 

        /// <typeparam name="T"></typeparam> 

        /// <param name="list"></param> 

        /// <returns></returns> 

        public static DataTable ToDataTable<T>(this IEnumerable<T> list,params string[] tableName)

        {

            //创建属性的集合 

            List<PropertyInfo> pList = new List<PropertyInfo>();

            //获得反射的入口 

            Type type = typeof(T);

            string tname = "Table1";

            if (tableName.Length >= 1)

            {

                tname = tableName[0];

            }

            DataTable dt = new DataTable(tname);

            //把所有的public属性加入到集合 并添加DataTable的列 

            Array.ForEach<PropertyInfo>(type.GetProperties(), p =>

            {

                pList.Add(p); 

                var theType=p.PropertyType;

                //处理可空类型

                if (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))

                {

                    dt.Columns.Add(p.Name,Nullable.GetUnderlyingType(theType));

                }

                else

                {

                    dt.Columns.Add(p.Name, theType);

                }

            });

            foreach (var item in list)

            {

                //创建一个DataRow实例 

                DataRow row = dt.NewRow();

                //给row 赋值 

                pList.ForEach(p =>

                {

                    var v=p.GetValue(item, null);

                    row[p.Name] = v==null ? DBNull.Value : v;

                    

                });

                //加入到DataTable 

                dt.Rows.Add(row);

            }

            return dt;

        }

}

}

 

你可能感兴趣的:(Datatable)