使用 EFW 和 ViewModel 插入数据库时,无法将类型"System.DateTime?"隐式转换为"System.DateTime"



我正在处理这个ASP.NET Core MVC项目,当我收到此错误时,我正在尝试将值从form保存到Database中:

无法将类型"System.DateTime

?"隐式转换为"System.DateTime"。存在显式转换(您是否缺少强制转换?

我在"视图模型"中通过以下方式使用 ? nullable FromDateToDate设置为:

视图模型:

public class ILViewModel
{
    ...
    ...
    public DateTime? FromDate { get; set; }
    public DateTime? ToDate { get; set; }
}

Controller - POST Method中,我通过以下方式向Database添加值:

控制器:

if (ModelState.IsValid)
{
    ...
    historyObj.FromDate = locationsHistoryVM.FromDate;
    historyObj.ToDate = locationsHistoryVM.ToDate;
}

怎么办?

您需要从可为空的对象中获取值。 那么你不会得到错误

if (ModelState.IsValid)
{
    ...
    historyObj.FromDate = locationsHistoryVM.FromDate.Value;
    historyObj.ToDate = locationsHistoryVM.ToDate.Value;
}

相关内容

最新更新