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

标签 c# asp.net-mvc entity-framework datetime

我有一个 Controller :

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

模型:

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; }}
}

还有一个 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>
}

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

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

model-controller-view 是从一本书中一对一复制过来的。

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

最佳答案

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

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

您可以:

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

B) 将模型中的类型更改为 datetime2,方法是:

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

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

关于c# - 将 datetime2 数据类型转换为 datetime 数据类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16298616/

相关文章:

c# - 访问 C#/WPF 中 IMultiValueConverter.ConvertBack() 中的绑定(bind)数据

javascript - jQuery 将带有 ajax 的文件发送到 MVC Controller

entity-framework - Entity Framework : Add Properties/Entities during runtime

c# - 如果从 pendrive 或服务器执行 Entity Framework 失败

c# - 使用 JSON.Net 序列化数组时忽略重复项

c# - 通用存储库的依赖注入(inject)

c# - 接口(interface)依赖层次结构

c# - 在 ASP.NET MVC 中以编程方式验证模型列表

asp.net - 使用 IIS 而不是 IIS Express 会加快本地运行的 VS2013 WebAP 应用程序的启动时间吗?

c# - dotnet ef 数据库更新无法加载文件或程序集“Microsoft.Extensions.FileProviders.Abstractions”