我正在尝试将通用集合(列表)转换为DataTable。我发现以下代码可以帮助我做到这一点:
// Sorry about indentation public class CollectionHelper { private CollectionHelper() { } // this is the method I have been using public static DataTable ConvertTo<T>(IList<T> list) { DataTable table = CreateTable<T>(); Type entityType = typeof(T); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (T item in list) { DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) { row[prop.Name] = prop.GetValue(item); } table.Rows.Add(row); } return table; } public static DataTable CreateTable<T>() { Type entityType = typeof(T); DataTable table = new DataTable(entityType.Name); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (PropertyDescriptor prop in properties) { // HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES table.Columns.Add(prop.Name, prop.PropertyType); } return table; } }
我的问题是,当我将MySimpleClass的属性之一更改为可为空的类型时,出现以下错误:
DataSet does not support System.Nullable<>.
如何在班级中使用可空属性/字段来实现此目的?
然后大概您需要使用将它们提升为不可为空的形式Nullable.GetUnderlyingType,并可能将一些null值更改为DbNull.Value…
Nullable.GetUnderlyingType
null
DbNull.Value
将分配更改为:
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
并且将列添加为:
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType( prop.PropertyType) ?? prop.PropertyType);
而且有效。(??是null运算符;如果非null,它将使用第一个操作数,否则将评估并使用第二个操作数)
??