LINQ returns System.Data.SqlTypes.SqlNullValueException. Why?

Corey Fleig 530 Reputation points
2026-01-14T20:25:52.73+00:00

I'm learning LINQ, and trying to fetch data from a SQL Server database. All I'm trying to do is fetch data from one datetime field that is defined as nullable, where I know the field value is set to null.

Here's my statement:

var query = from cm in mydb.myTable
where cm.key == 1
select cm.ADMDATE;


But this won't execute because it returns EntityQueryable. So I changed the statement:

var query = (from cm in mydb.myTable
where cm.key == 1
select cm.ADMDATE).FirstOrDefault();


This is where I get the runtime error: System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.' So I tried a suggestion from AI:

var query = (from cm in mydb.myTable
where cm.key == 1
select new myClass
{
   myDate = cm.ADMDATE.HasValue ? c.ADMDATE.Value : (DateTime?)null
}).FirstOrDetault();


You guessed it! .HasValue won't compile.

Any recommendations on how to get LINQ to execute?

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author
Anonymous
2026-01-15T06:30:59.8733333+00:00

Hello @Corey Fleig ,

I suspect your entity class (the one mapped to your database table) likely has a non-nullable DateTime property. You should look for the entity class that your myTable DbSet uses:

public class YourTableEntity  
{
    public int Id { get; set; }
    public DateTime? somedate { get; set; }  // ← Added nullable
}

And the result class should correctly define the DateTime property as nullable as well:

public class myClass
{
    public DateTime? MyDate { get; set; }
}

Everything else is the same as before, you can even query for NULL values without any issues:

var query = from c in myTable
            where Id == 1
            select new myClass { myDate = c.somedate };

var result = query.FirstOrDefault();
if (result?.myDate.HasValue == true)
{
    Console.WriteLine($"Date: {result.myDate.Value}");
}
else
{
    Console.WriteLine("Date is NULL");
}

var nullRecords = from c in myTable
                  where c.somedate == null
                  select new myClass { myDate = c.somedate };

If you still face issues, please share the relevant parts of your entity class and the result class so I can help you further.

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.