C# 首先使用EF代码将datetime2数据类型转换为datetime数据类型错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10585214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:23:10  来源:igfitidea点击:

conversion of a datetime2 data type to a datetime data type error with EF Code first?

c#sql-server-2008entity-frameworkef-code-firstentity-framework-4.3

提问by Mohammad Zare

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 的类型是我的数据库中的日期时间。这是我使用上述代码时发生的错误!:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围。

please help me. thanks.

请帮我。谢谢。

采纳答案by Blast_dan

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 日期时间列的值。这里给出的答案将阻止转换失败。

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 类型。我不完全知道为什么他们首先编写代码是生成日期时间列而不是日期时间2

Here is an example to explicitly map your Datetime columns to datetime2 in SQL

这是在 SQL 中将日期时间列显式映射到 datetime2 的示例

Using DateTime properties in Code-First Entity Framework and SQL Server

在 Code-First Entity Framework 和 SQL Server 中使用 DateTime 属性

回答by Daniel

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.

另一个解决方案是无论如何都要在构造函数中初始化该字段。