DataSet does not support System.Nullable
-
I am trying to build a DataTable from a TList, which is a collection of T business objects. I am using reflection to get all the properties of T, and then loop through them creating DataColumn objects. However, I get an error when I try and create a new column where a property of T is nullable. Is there a quick way around this? Looking at the type name for a nullable property of T is also pretty confusing, as the type name is "Nullable`1".
"A little learning is a dangerous thing; drink deep, or taste not the Pierian spring: there shallow draughts intoxicate the brain, and drinking largely sobers us again.", by Alexander Pope My New Blog
-
I am trying to build a DataTable from a TList, which is a collection of T business objects. I am using reflection to get all the properties of T, and then loop through them creating DataColumn objects. However, I get an error when I try and create a new column where a property of T is nullable. Is there a quick way around this? Looking at the type name for a nullable property of T is also pretty confusing, as the type name is "Nullable`1".
"A little learning is a dangerous thing; drink deep, or taste not the Pierian spring: there shallow draughts intoxicate the brain, and drinking largely sobers us again.", by Alexander Pope My New Blog
You need to get the underlying type, e.g.:
// Get PropertyInfo[] properties from T
foreach (PropertyInfo propInfo in properties)
{
Type propType = propInfo.PropertyType;
if (propType.IsGenericType &&
propType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propType = Nullable.GetUnderlyingType(propType);
}
// Create DataColumn from propType, etc. ...
} -
You need to get the underlying type, e.g.:
// Get PropertyInfo[] properties from T
foreach (PropertyInfo propInfo in properties)
{
Type propType = propInfo.PropertyType;
if (propType.IsGenericType &&
propType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propType = Nullable.GetUnderlyingType(propType);
}
// Create DataColumn from propType, etc. ...
}Thanks Lisa, I actually did discover that a while after posting. I should have updated. :-O
-
You need to get the underlying type, e.g.:
// Get PropertyInfo[] properties from T
foreach (PropertyInfo propInfo in properties)
{
Type propType = propInfo.PropertyType;
if (propType.IsGenericType &&
propType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propType = Nullable.GetUnderlyingType(propType);
}
// Create DataColumn from propType, etc. ...
}instead of your
if (propType.IsGenericType &&
propType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propType = Nullable.GetUnderlyingType(propType);
}you could also do
column.DataType = Nullable.GetUnderlyingType(PropertyType) ?? PropertyType;
depending on your knowledge about the ?? operator and your preferences it could improve the readability