Problem
Given the following:
class MyClass
{
public DateTime DateTime { get; set; }
}
and a queryable, where MyTable.NullableDateTime is a DateTime? mapped to an SQL datetime:
IQueryable<MyTable> table = //something
Running the following produces an exception when the row's NullableDateTime column is NULL:
table.Select(row => new MyClass
{
DateTime = Convert.ToDateTime(row.NullableDateTime)
}).ToArray();
The error is:
InvalidOperationException
The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type.
What I've Tried
Looking at the generated SQL:
CONVERT(DateTime,[t0].[NullableDateTime]) AS [NullableDateTime]Running the query before performing the
Select. This works around the problem, but I don't want to run this on the client side just to work around the problem.Using
row.GetDefaultValue()instead ofConvert.ToDateTime. This yields a different error:SqlException
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
The
GetDefaultValuemethod call is converted to the following SQL:COALESCE([t0].[NullableDateTime],'1/01/0001 12:00:00 AM') AS [NullableDateTime]
NullableDateTime? I assume you can't change the type in the database...datetimemapped to a .NETDateTime?.MyClass.DateTimenot nullable? You wouldn't need any conversion if it was.default(DateTime)because you're within .Net. Bad thing is, you'll have to check forDateTime.MinValuewhereMyClass.DateTimeis addressed.