SqlException for datetime column

94 views Asked by At

I have the following LINQ query :

var studentRecords = context.Students
                            .Include(i => i.StudentsAdmission)
                            .Where(w => !w.StudentsAdmission.Any() 
                                        || w.StudentsAdmission.Any(s => s.AdmissionDate == null || s.AdmissionDate == DateTime.MinValue))
                            .ToList();

The AdmissionDate column is defined as [AdmissionDate] [datetime] NOT NULL.

This query is throwing an error :

Error Number:242,State:3,Class:16
Microsoft.Data.SqlClient.SqlException (0x80131904): The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows) at Microsoft.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more) at Microsoft.Data.SqlClient.SqlDataReader.Read() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.Enumerator.MoveNext() ClientConnectionId:3d199aef-d03e-4041-82c8-87cfa6212098 Error Number:242,State:3,Class:16

I have checked the table and the data seems to be right. What am I missing?

EDIT: I do not want to change the column to nullable because this will end up causing a lot of other changes.

1

There are 1 answers

3
Thiago Custodio On

I think the problem is because DateTime.MinValue translates to 0001-01-01, a value outside the range SQL Server can handle.