编辑时,将datetime2数据类型转换为datetime数据类型导致值超出范围Error

本文关键字:Error 范围 数据类型 datetime datetime2 数据 类型转换 编辑 | 更新日期: 2023-09-27 18:25:25

我的模型中有这个字段:

public DateTime ATime{ get; set; }

在创建控制器上,我可以使用日期选择器选择日期,它成功地创建了。

但是当我尝试编辑对象时,我在标题中得到了异常。我的编辑代码是默认的编辑代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="AID,ATime")] Project project)
{
            if (ModelState.IsValid)
            {
                db.Entry(project).State = EntityState.Modified;
                db.SaveChanges(); // I get exception at this line.
                return RedirectToAction("Index");
            }
            return View(project);
}

我怎样才能摆脱这个例外?谢谢

编辑时,将datetime2数据类型转换为datetime数据类型导致值超出范围Error

Datetime2的范围比datetime大。你确定要设置的新值符合日期时间的范围吗?

(此外,datetime是一种不符合ANSI的遗留类型。无论如何,我都会将数据库中的基础类型更改为datetime2。)。http://blogs.msdn.com/b/cdnsoldevs/archive/2011/06/22/why-you-should-never-use-datetime-again.aspx)

更改模式代码如下:-

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime ATime{ get; set; }

此外,日期应在以下范围内:最短日期为:1753年1月1日最长日期为:9999年12月31日

我认为您没有专门使用datetime2类型。因此,您可以使用数据注释将日期时间类型分配给您的模型属性,如下所示。

[DataType(DataType.DateTime)]
public DateTime ATime { get; set; }