2

出于某种特殊原因,我不得不将数据存储到 DataTable 中,并意识到它不支持可为空的类型:抛出 System.NotSupportedException:DataSet 不支持 System.Nullable<>。有没有比枚举类型和为每个可空类型编写自定义代码更有效的转换方法?

4

1 回答 1

2

但它支持可为空的类型,默认情况下AllowDbNulltrue

var table = new DataTable();
table.Columns.Add("NullableInt", typeof(int));
table.Rows.Add(1);
table.Rows.Add(2);
table.Rows.Add(3);
table.Rows.Add((int?)null);

使用支持可为空类型的DataRow 扩展方法,例如:

foreach(DataRow row in table.Rows)
{
    int? value = row.Field<Int32?>("NullableInt");
    // modify the value with SetField:
    row.SetField<Int32?>("NullableInt", null); 
    // or: 
    row.SetField("NullableInt", (int?)null);
}
于 2013-09-10T13:38:26.380 回答