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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16298616/
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-10 00:41:17  来源:igfitidea点击:

The conversion of a datetime2 data type to a datetime data type Error

c#asp.net-mvcentity-frameworkdatetime

提问by Alexandra Orlov

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 EndTimefield so I won't have this error?

我需要在EndTime字段中输入什么格式才能避免出现此错误?

采纳答案by mattytommo

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).

错误是因为您实际上没有正确设置这些值,请确保根据您的应用程序区域设置来设置它们。(例如 dd/mm/yyyy 表示en-GB,mm/dd/yyyy 表示en-US)。

It also looks like your database has been set up to use a datetime2column and nota datetimecolumn.

它也像你的数据库已设置为使用一datetime2列,并没有datetime列。

You can either:

您可以:

A) Modify the database to change the type from datetime2to 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; }

回答by Amit Rai Sharma

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 将创建不可为空的列。尝试将这些属性转换为可为空的日期时间。

回答by Rusty Nail

I also struck this problem.

我也遇到了这个问题。

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range valueis 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

我在包管理器控制台中启用了数据库迁移 -> 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

然后在包管理器控制台中运行数据库更新 -> 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 的最后一个版本中没有修复这样一个常见的问题超出了我的理解。

回答by Pavan

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 添加到服务层中的联系人实体时,我遇到了类似的错误。通过从控制器添加参数解决了该问题。请尝试从控制器添加参数。

回答by Asaf

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 时将未分配的 DateTime 成员保存到数据库时遇到了同样的问题。我在这里阅读了答案,我了解到可以通过将成员声明为可为空来解决它。我试过了,它奏效了!所以这是一个代码快照,对于那些需要它的人:

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;

回答by Beanwah

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.

我在数据库中的 DateCreated 上有一个默认的 getdate() 值。我没有在 EF 中设置值,因为我认为我不需要。一旦我在插入时通过 EF 传递了值,错误就消失了。为什么首先会出现这个错误?我从来没有想过。

回答by Bassem

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

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

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.

字段 StartTime 必须介于 1/1/1753 12:00:00 AM 和 12/31/9999 12:00:00 AM 之间。

回答by Nathan Agersea

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.

我的问题的原因是使用禁用属性与只读。表单不会将禁用的输入值提交给导致空值的控制器,从而导致最小日期/时间值。

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>