日期时间列的 SqlException

问题描述 投票:0回答:1

我有以下 LINQ 查询:

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();

AdmissionDate
列定义为
[AdmissionDate] [datetime] NOT NULL

此查询抛出错误:

错误号:242,状态:3,类别:16
Microsoft.Data.SqlClient.SqlException (0x80131904):将 varchar 数据类型转换为 datetime 数据类型导致值超出范围。

在Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔breakConnection,Action

1 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.SingleQueryingEnumerable
1.Enumerator.MoveNext() 客户端连接 ID:3d199aef-d03e-4041-82c8-87cfa6212098 错误号:242,状态:3,类别:16

我检查了表格,数据似乎是正确的。我错过了什么?

编辑:我不想将该列更改为可为空,因为这最终会导致许多其他更改。

c# sql-server linq asp.net-core entity-framework-core
1个回答
0
投票

我认为问题是因为 DateTime.MinValue 转换为 0001-01-01,该值超出了 SQL Server 可以处理的范围。

var minValidAdmissionDate = new DateTime(1753, 1, 1); // min sql server date

var studentRecords = context.Students
                            .Include(i => i.StudentsAdmission)
                            .Where(w => !w.StudentsAdmission.Any() 
                                        || w.StudentsAdmission.Any(s => s.AdmissionDate < minValidAdmissionDate))
                            .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.