Hi @Corey Fleig ,
Thanks for reaching out.
This one is definitely confusing at first glance, especially since you’re already doing the “right” thing by using DateTime? in your model. The key thing to know is that the exception isn’t coming from your model at all - it happens earlier, while the data is being read from SQL.
What’s going on behind the scenes is that LINQ-to-SQL / ADO.NET doesn’t read datetime columns directly as DateTime?. It uses SQL types (like SqlDateTime) internally. When the value in the database is NULL, trying to access that value without checking first causes System.Data.SqlTypes.SqlNullValueException. That happens before your nullable property ever gets a chance to receive null, which is why enabling or disabling <Nullable>enable</Nullable> doesn’t change anything.
To avoid the exception, you need to make the null handling explicit in the projection so LINQ knows how to translate it safely. For example:
var query =
from c in myTable
where Id == 1
select new myClass
{
MyDate = c.somedate == null ? (DateTime?)null : c.somedate
};
If somedate is exposed as a SQL type (for example SqlDateTime), the same idea applies - just make sure you only read the value after checking it’s not null:
MyDate = c.somedate.HasValue ? c.somedate.Value : (DateTime?)null
A couple of clarifications that may help: the database schema you described (datetime null) is perfectly valid, and your DateTime? property is also correct. The issue isn’t with nullable C# types, and it’s not something the nullable context setting controls. It’s simply how SQL NULL values are materialized by this data access layer.
For context, if this were EF Core, you wouldn’t see this behavior - EF Core maps SQL NULL to DateTime? automatically. This exception is specific to LINQ-to-SQL / lower-level ADO.NET handling.
Hope this helps! If my answer was helpful - kindly follow the instructions here so others with the same problem can benefit as well.