Search code examples
asp.net-mvcentity-frameworkasp.net-core-mvcviewmodelasp.net-mvc-viewmodel

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime' when inserting into Database using EFW and ViewModel


I am working on this ASP.NET Core MVC project where I am trying to save the values from form into Database when I am getting this error:

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

I have set FromDate and ToDate as nullable using ? in the following way in the `ViewModel:

ViewModel:

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

In Controller - POST Method, I am adding values to the Database in the following manner:

Controller:

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

What to do?


Solution

  • You need to get value from nullable object. then you wont get error

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