I'm using EF Code first with my asp.net mvc application. here is my code:
我首先在我的asp.net mvc应用程序中使用EF代码。这是我的代码:
Request.RequestDate = DateTime.Now;
the type of RequestDate is datetime in my database. and this is error that occurred when i use the above code!:
RequestDate的类型是我的数据库中的datetime。这是我使用上面的代码时发生的错误!:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
将datetime2数据类型转换为日期时间数据类型会导致超出范围的值。
please help me. thanks.
请帮帮我。谢谢。
2 个解决方案
#1
11
Edit:
编辑:
How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?
如何使用DbContext和SetInitializer修复datetime2超出范围的转换错误?
The issue is that you are trying to save a value that cannot fit in a SQL datetime column. the answer givin here will stop the conversion from failing.
问题是您正在尝试保存不适合SQL datetime列的值。这里给出的答案将阻止转换失败。
or in your Database change the columns to be type datetime2. I don't exactly know why they code first is generating datetime columns instead of datetime2
或者在数据库中将列更改为类型datetime2。我不知道为什么他们的代码首先是生成datetime列而不是datetime2
Here is an example to explicitly map your Datetime columns to datetime2 in SQL
下面是一个在SQL中将Datetime列显式映射到datetime2的示例
Using DateTime properties in Code-First Entity Framework and SQL Server
在代码优先实体框架和SQL Server中使用DateTime属性
#2
6
On my side it was because the datetime was not nullable and in some situation the field was not initialized in the constructor. I solved this by setting my field as nullable
在我这边是因为日期时间不可为空,在某些情况下,字段没有在构造函数中初始化。我通过将我的字段设置为可空来解决了这个问题
public DateTime? MyDate { get; set; }
Another solution would be to initialize the field in the constructor no matter what.
另一种解决方案是在构造函数中初始化字段,无论如何。
#1
11
Edit:
编辑:
How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?
如何使用DbContext和SetInitializer修复datetime2超出范围的转换错误?
The issue is that you are trying to save a value that cannot fit in a SQL datetime column. the answer givin here will stop the conversion from failing.
问题是您正在尝试保存不适合SQL datetime列的值。这里给出的答案将阻止转换失败。
or in your Database change the columns to be type datetime2. I don't exactly know why they code first is generating datetime columns instead of datetime2
或者在数据库中将列更改为类型datetime2。我不知道为什么他们的代码首先是生成datetime列而不是datetime2
Here is an example to explicitly map your Datetime columns to datetime2 in SQL
下面是一个在SQL中将Datetime列显式映射到datetime2的示例
Using DateTime properties in Code-First Entity Framework and SQL Server
在代码优先实体框架和SQL Server中使用DateTime属性
#2
6
On my side it was because the datetime was not nullable and in some situation the field was not initialized in the constructor. I solved this by setting my field as nullable
在我这边是因为日期时间不可为空,在某些情况下,字段没有在构造函数中初始化。我通过将我的字段设置为可空来解决了这个问题
public DateTime? MyDate { get; set; }
Another solution would be to initialize the field in the constructor no matter what.
另一种解决方案是在构造函数中初始化字段,无论如何。