将datetime2数据类型转换为datetime数据类型错误。

时间:2021-07-16 16:42:47

I have a controller:

我有一个控制器:

[HttpPost]
public ActionResult Create(Auction auction)
{
    var db = new EbuyDataContext();
    db.Auctions.Add(auction);
    db.SaveChanges();
    return View(auction);
}

A model:

一个模型:

public class Auction
{
        public long Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public decimal StartPrice { get; set; }
        public decimal CurrentPrice { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }}
}

And a view:

和一个视图:

@model Ebuy.Website.Models.Auction
@using (Html.BeginForm())
{
    <p>
        //All the information fields...
        @Html.LabelFor(model => model.EndTime)
        @Html.EditorFor(model => model.EndTime)
    </p>
}

When I try to run it I receive the error:

当我试图运行它时,我收到了错误:

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

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

The model-controller-view is from a book copied one-to-one.

模型-控制器-视图是从一本书一对一复制的。

What is the format that I need to enter to the EndTime field so I won't have this error?

我需要输入到EndTime字段的格式是什么,这样我就不会有这个错误了?

9 个解决方案

#1


21  

The error is because you haven't actually set those values correctly, make sure you set them depending on your applications locale. (e.g. dd/mm/yyyy for en-GB, mm/dd/yyyy for en-US).

错误是由于您没有正确地设置这些值,所以要根据您的应用程序语言环境设置它们。(例如en-GB的dd/mm/yyyy, en-US的mm/dd/yyy)。

It also looks like your database has been set up to use a datetime2 column and not a datetime column.

看起来您的数据库已经被设置为使用datetime2列而不是datetime列。

You can either:

你可以:

A) Modify the database to change the type from datetime2 to datetime

A)修改数据库,将类型从datetime2修改为datetime

B) Change the types in your Model to be datetime2, by doing:

B)通过以下操作将模型中的类型更改为datetime2:

[Column(TypeName = "DateTime2")]
public DateTime StartTime { get; set; }

[Column(TypeName = "DateTime2")]
public DateTime EndTime { get; set; }

#2


13  

I had the same problem when I tried to save an unassigened DateTime member to the DB, while using EntityFramework. I read the answers here, and I learned that it can be solved by declaring the member as nullable. I tried it, and it worked! So here is a code snap, for those who need it:

当我尝试在使用EntityFramework时,将一个unassigened DateTime成员保存到DB时,也遇到了同样的问题。我在这里读了答案,我知道它可以通过声明成员为nullable来解决。我试过了,成功了!这是一个代码快照,对于那些需要它的人:

public Nullable<DateTime> MyDateTime { get; set; }

or

public DateTime? MyDateTime { get; set; }

Later I could use it like bellow:

之后我可以像贝娄一样使用它:

if(MyDateTime.HasValue)
{
    DoBlaBla(MyDateTime.Value);
}

or just assign a value to it like nothing had happen...

或者只是给它赋值,就像什么都没发生过一样……

MyDateTime = DateTime.Now;

#3


3  

Does your columns with datetime2 datatype accepts null values. If not then you might get this error when you are not assigning a value to these columns.

使用datetime2数据类型的列是否接受空值。如果不是,那么当您没有为这些列赋值时,您可能会得到这个错误。

By default the CodeFirst will make non nullable columns if your model does not use nullable properties. Try converting these properties to nullable datetime.

默认情况下,如果模型不使用可空属性,CodeFirst将生成不可空列。尝试将这些属性转换为nullable datetime。

#4


0  

I also struck this problem.

我也遇到了这个问题。

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value is a very un-useful error that one receives.

将datetime2数据类型转换为datetime数据类型导致值超出范围是一个非常无用的错误。

To resolve the problem I had to do the following (Using the above example):

为了解决这个问题,我必须做以下的事情(使用上面的例子):

One can find the Package Manager Console from -> Tools -> Library Package Manager -> Package Manager Console

可以从->工具->库包管理器->包管理器控制台找到包管理器控制台

I enabled Database Migrations in Package Manager Console -> Enable-Migrations

我在包管理器控制台启用了数据库迁移——>支持迁移

Then added the below code in the Controller Class:

然后在控制器类中添加下面的代码:

public class Auction
{
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public decimal StartPrice { get; set; }
public decimal CurrentPrice { get; set; }

// My Edit to the code Start -->
public Nullable<DateTime> StartTime { get; set; }
public Nullable<DateTime> EndTime { get; set; }}
// My Edit to the code Finish <--
}

Then in the Models Class:

然后在模型类中:

[HttpPost]

// My Edit to the code Start -->
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]]
// My Edit to the code Finish <--

public ActionResult Create(Auction auction)
{

// My Edit to the code Start -->
if(ModelState.IsValid)
{
// Only Apply the DateTime if the Action is Valid...
auction.StartTime = DateTime.Now;
}
// My Edit to the code Finish <--

var db = new EbuyDataContext();
db.Auctions.Add(auction);
db.SaveChanges();
return View(auction);
}

Then Add to the Database the changes in the Package Manager Console -> Add-Migration (Your Change goes here)

然后将包管理器控制台中的更改添加到数据库中——>扩展迁移(您的更改在这里)

Then run a Database Update in the Package Manager Console -> Update-Database

然后在包管理器控制台——>更新数据库中运行数据库更新

Its important to see that the Data that the Database see's is correct in the above implementation:

重要的是要确保数据库所看到的数据在上述实现中是正确的:

E.G: 17/06/2013 12:00:00 AM

This error is an amazingly stupid error but it seems to have caught a lot of people out including my self. Now I know why this error occurs it seems that it is easy to fix and get around but why such a common issue would not be fixed in the last release of MVC is beyond my comprehension.

这个错误是一个非常愚蠢的错误,但它似乎已经抓住了很多人,包括我自己。现在我知道为什么会出现这个错误了,它看起来很容易修复,但是为什么在MVC的最后一个版本中没有解决这个常见问题是我无法理解的。

#5


0  

I got the similar error when i was trying to add change_date to my contact entity in the service layer. The issue was resolved by adding the parameter from controller. Please try to add the parameter from Controller.

当我试图将change_date添加到服务层中的联系人实体时,我得到了类似的错误。问题通过添加控制器的参数得到解决。请尝试添加控制器的参数。

#6


0  

I had a default getdate() value on DateCreated in the DB. I wasn't setting the value in EF because I didn't think I needed to. Once I passed in the value through EF on the insert then the error went away. Why is that error there in the first place? I never figured that out.

我在DB中对DateCreated的数据有一个默认的getdate()值。我没有在EF中设置值,因为我不认为我需要这样做。当我在insert上通过EF传递值时,错误就消失了。为什么会有这个错误呢?我从来没想过。

#7


0  

I recommend making the DateTime property nullable and also using attribute validation to make sure the value is within the acceptable range.

我建议将DateTime属性设为nullable,并使用属性验证来确保值在可接受的范围内。

I created a custom attribute inherited from RangeAttribute to validate the date value.

我创建了一个从RangeAttribute继承的自定义属性来验证日期值。

public class DbDateRangeAttribute
    : RangeAttribute
{
    public DbDateRangeAttribute()
        : base(typeof(DateTime), SqlDateTime.MinValue.Value.ToShortDateString(), SqlDateTime.MaxValue.Value.ToShortDateString())
    { }
}

And then you use the attribute like that

然后像这样使用属性

[DbDateRange]
public DateTime? StartTime { get; set; }

Like that, if the user enters a value outside the range of SqlDateTime (probably because of a client-side date picker issue), he will get a meaningful error message like the following:

这样,如果用户输入的值超出了SqlDateTime的范围(可能是由于客户端日期选择器问题),他将得到一条有意义的错误消息,如下所示:

The field StartTime must be between 1/1/1753 12:00:00 AM and 12/31/9999 12:00:00 AM.

场启动时间必须在1/1753 12:00:00到12/31/9999 12:00:00之间。

#8


0  

I ran into this with my system fields (created_on, modified_on) even though my model was defined properly.

我在系统字段(created_on、modified_on)中遇到了这个问题,尽管我的模型定义正确。

The cause of my issue was using the disabled attribute vs readonly. Forms will not submit disabled input values to the controller which resulted in the null value which, in turn, resulted in the min date/time value.

我的问题是使用禁用属性vs readonly。表单不会向控制器提交已禁用的输入值,从而导致null值,从而导致最小日期/时间值。

Wrong:

错误的:

<div class="form-group">
    @Html.LabelFor(model => model.CreatedOn, htmlAttributes: new { @class = "control-label col-lg-3" })
    <div class="col-lg-9">
        @Html.EditorFor(model => model.CreatedOn, new { htmlAttributes = new { @class = "form-control", disabled="disabled" } })
        @Html.ValidationMessageFor(model => model.CreatedOn, "", new { @class = "text-danger" })
    </div>
</div>

Right:

正确的:

<div class="form-group">
    @Html.LabelFor(model => model.CreatedOn, htmlAttributes: new { @class = "control-label col-lg-3" })
    <div class="col-lg-9">
        @Html.EditorFor(model => model.CreatedOn, new { htmlAttributes = new { @class = "form-control", @readonly="readonly" } })
        @Html.ValidationMessageFor(model => model.CreatedOn, "", new { @class = "text-danger" })
    </div>
</div>

#9


0  

This post - Solution to: “The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value” with Entity Framework when calling SaveChanges - proposes to use the attribute. It solved the issue for me.

这个后解决方案:“将datetime2数据类型转换为datetime数据类型会导致一个超出范围的值”,在调用SaveChanges时使用实体框架。它帮我解决了这个问题。

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public Nullable<System.DateTime> Created { get; set; }

#1


21  

The error is because you haven't actually set those values correctly, make sure you set them depending on your applications locale. (e.g. dd/mm/yyyy for en-GB, mm/dd/yyyy for en-US).

错误是由于您没有正确地设置这些值,所以要根据您的应用程序语言环境设置它们。(例如en-GB的dd/mm/yyyy, en-US的mm/dd/yyy)。

It also looks like your database has been set up to use a datetime2 column and not a datetime column.

看起来您的数据库已经被设置为使用datetime2列而不是datetime列。

You can either:

你可以:

A) Modify the database to change the type from datetime2 to datetime

A)修改数据库,将类型从datetime2修改为datetime

B) Change the types in your Model to be datetime2, by doing:

B)通过以下操作将模型中的类型更改为datetime2:

[Column(TypeName = "DateTime2")]
public DateTime StartTime { get; set; }

[Column(TypeName = "DateTime2")]
public DateTime EndTime { get; set; }

#2


13  

I had the same problem when I tried to save an unassigened DateTime member to the DB, while using EntityFramework. I read the answers here, and I learned that it can be solved by declaring the member as nullable. I tried it, and it worked! So here is a code snap, for those who need it:

当我尝试在使用EntityFramework时,将一个unassigened DateTime成员保存到DB时,也遇到了同样的问题。我在这里读了答案,我知道它可以通过声明成员为nullable来解决。我试过了,成功了!这是一个代码快照,对于那些需要它的人:

public Nullable<DateTime> MyDateTime { get; set; }

or

public DateTime? MyDateTime { get; set; }

Later I could use it like bellow:

之后我可以像贝娄一样使用它:

if(MyDateTime.HasValue)
{
    DoBlaBla(MyDateTime.Value);
}

or just assign a value to it like nothing had happen...

或者只是给它赋值,就像什么都没发生过一样……

MyDateTime = DateTime.Now;

#3


3  

Does your columns with datetime2 datatype accepts null values. If not then you might get this error when you are not assigning a value to these columns.

使用datetime2数据类型的列是否接受空值。如果不是,那么当您没有为这些列赋值时,您可能会得到这个错误。

By default the CodeFirst will make non nullable columns if your model does not use nullable properties. Try converting these properties to nullable datetime.

默认情况下,如果模型不使用可空属性,CodeFirst将生成不可空列。尝试将这些属性转换为nullable datetime。

#4


0  

I also struck this problem.

我也遇到了这个问题。

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value is a very un-useful error that one receives.

将datetime2数据类型转换为datetime数据类型导致值超出范围是一个非常无用的错误。

To resolve the problem I had to do the following (Using the above example):

为了解决这个问题,我必须做以下的事情(使用上面的例子):

One can find the Package Manager Console from -> Tools -> Library Package Manager -> Package Manager Console

可以从->工具->库包管理器->包管理器控制台找到包管理器控制台

I enabled Database Migrations in Package Manager Console -> Enable-Migrations

我在包管理器控制台启用了数据库迁移——>支持迁移

Then added the below code in the Controller Class:

然后在控制器类中添加下面的代码:

public class Auction
{
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public decimal StartPrice { get; set; }
public decimal CurrentPrice { get; set; }

// My Edit to the code Start -->
public Nullable<DateTime> StartTime { get; set; }
public Nullable<DateTime> EndTime { get; set; }}
// My Edit to the code Finish <--
}

Then in the Models Class:

然后在模型类中:

[HttpPost]

// My Edit to the code Start -->
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]]
// My Edit to the code Finish <--

public ActionResult Create(Auction auction)
{

// My Edit to the code Start -->
if(ModelState.IsValid)
{
// Only Apply the DateTime if the Action is Valid...
auction.StartTime = DateTime.Now;
}
// My Edit to the code Finish <--

var db = new EbuyDataContext();
db.Auctions.Add(auction);
db.SaveChanges();
return View(auction);
}

Then Add to the Database the changes in the Package Manager Console -> Add-Migration (Your Change goes here)

然后将包管理器控制台中的更改添加到数据库中——>扩展迁移(您的更改在这里)

Then run a Database Update in the Package Manager Console -> Update-Database

然后在包管理器控制台——>更新数据库中运行数据库更新

Its important to see that the Data that the Database see's is correct in the above implementation:

重要的是要确保数据库所看到的数据在上述实现中是正确的:

E.G: 17/06/2013 12:00:00 AM

This error is an amazingly stupid error but it seems to have caught a lot of people out including my self. Now I know why this error occurs it seems that it is easy to fix and get around but why such a common issue would not be fixed in the last release of MVC is beyond my comprehension.

这个错误是一个非常愚蠢的错误,但它似乎已经抓住了很多人,包括我自己。现在我知道为什么会出现这个错误了,它看起来很容易修复,但是为什么在MVC的最后一个版本中没有解决这个常见问题是我无法理解的。

#5


0  

I got the similar error when i was trying to add change_date to my contact entity in the service layer. The issue was resolved by adding the parameter from controller. Please try to add the parameter from Controller.

当我试图将change_date添加到服务层中的联系人实体时,我得到了类似的错误。问题通过添加控制器的参数得到解决。请尝试添加控制器的参数。

#6


0  

I had a default getdate() value on DateCreated in the DB. I wasn't setting the value in EF because I didn't think I needed to. Once I passed in the value through EF on the insert then the error went away. Why is that error there in the first place? I never figured that out.

我在DB中对DateCreated的数据有一个默认的getdate()值。我没有在EF中设置值,因为我不认为我需要这样做。当我在insert上通过EF传递值时,错误就消失了。为什么会有这个错误呢?我从来没想过。

#7


0  

I recommend making the DateTime property nullable and also using attribute validation to make sure the value is within the acceptable range.

我建议将DateTime属性设为nullable,并使用属性验证来确保值在可接受的范围内。

I created a custom attribute inherited from RangeAttribute to validate the date value.

我创建了一个从RangeAttribute继承的自定义属性来验证日期值。

public class DbDateRangeAttribute
    : RangeAttribute
{
    public DbDateRangeAttribute()
        : base(typeof(DateTime), SqlDateTime.MinValue.Value.ToShortDateString(), SqlDateTime.MaxValue.Value.ToShortDateString())
    { }
}

And then you use the attribute like that

然后像这样使用属性

[DbDateRange]
public DateTime? StartTime { get; set; }

Like that, if the user enters a value outside the range of SqlDateTime (probably because of a client-side date picker issue), he will get a meaningful error message like the following:

这样,如果用户输入的值超出了SqlDateTime的范围(可能是由于客户端日期选择器问题),他将得到一条有意义的错误消息,如下所示:

The field StartTime must be between 1/1/1753 12:00:00 AM and 12/31/9999 12:00:00 AM.

场启动时间必须在1/1753 12:00:00到12/31/9999 12:00:00之间。

#8


0  

I ran into this with my system fields (created_on, modified_on) even though my model was defined properly.

我在系统字段(created_on、modified_on)中遇到了这个问题,尽管我的模型定义正确。

The cause of my issue was using the disabled attribute vs readonly. Forms will not submit disabled input values to the controller which resulted in the null value which, in turn, resulted in the min date/time value.

我的问题是使用禁用属性vs readonly。表单不会向控制器提交已禁用的输入值,从而导致null值,从而导致最小日期/时间值。

Wrong:

错误的:

<div class="form-group">
    @Html.LabelFor(model => model.CreatedOn, htmlAttributes: new { @class = "control-label col-lg-3" })
    <div class="col-lg-9">
        @Html.EditorFor(model => model.CreatedOn, new { htmlAttributes = new { @class = "form-control", disabled="disabled" } })
        @Html.ValidationMessageFor(model => model.CreatedOn, "", new { @class = "text-danger" })
    </div>
</div>

Right:

正确的:

<div class="form-group">
    @Html.LabelFor(model => model.CreatedOn, htmlAttributes: new { @class = "control-label col-lg-3" })
    <div class="col-lg-9">
        @Html.EditorFor(model => model.CreatedOn, new { htmlAttributes = new { @class = "form-control", @readonly="readonly" } })
        @Html.ValidationMessageFor(model => model.CreatedOn, "", new { @class = "text-danger" })
    </div>
</div>

#9


0  

This post - Solution to: “The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value” with Entity Framework when calling SaveChanges - proposes to use the attribute. It solved the issue for me.

这个后解决方案:“将datetime2数据类型转换为datetime数据类型会导致一个超出范围的值”,在调用SaveChanges时使用实体框架。它帮我解决了这个问题。

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public Nullable<System.DateTime> Created { get; set; }