Search code examples
c#asp.netasp.net-mvccrystal-reports

Passing value from Nullable Date Time to Date Time variable in Crystal Report


In my ASP.NET MVC & Entity Framework application, I created my database table column Approved_Date as nullable.

public DateTime? Approved_Date { get; set; }

Then when I calling data to the report I created a view model and created property as,

public DateTime ApprovedDateDM { get; set; }

In the query I cannot assign the Approved_Date value from the database table to the view model ApprovedDateDM. I'm getting an error

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

select new SuspensApprovedList {
     ApprovedDateDM = pa.Approved_Date, //Error
     ApprovedDateFM = se.FinanceApprovedDate, //Error
     ApproverDM = ae.EmpName,
     ApproverDessignationDM = ad.Designation,
     ApproverDessignationFM = d.Designation,
     ApproverFM = fe.EmpName,
}).ToList();

I could simply change the view model property to nullable and fix the issue, but when I pass this view model data to the Crystal Report I getting another error that Crystal Report won't allow nullable values.

Is there any way to fix this?


Solution

  • Try something like this

     select new SuspensApprovedList {
         ApprovedDateDM = pa.Approved_Date.HasValue?pa.Approved_Date : DateTime.MinValue, //or any default value you prefer.
         ApprovedDateFM = pa.FinanceApprovedDate.HasValue?pa.FinanceApprovedDate: DateTime.MinValue,
         ApproverDM = ae.EmpName,
         ApproverDessignationDM = ad.Designation,
         ApproverDessignationFM = d.Designation,
         ApproverFM = fe.EmpName,
    
     }).ToList();
    

    Or you can use

     select new SuspensApprovedList {
         ApprovedDateDM = pa.Approved_Date.GetValueOrDefault(), // You can pass the default value also like GetValueOrDefault(defaultDate)
         ApprovedDateFM = pa.FinanceApprovedDate.GetValueOrDefault(),
         ApproverDM = ae.EmpName,
         ApproverDessignationDM = ad.Designation,
         ApproverDessignationFM = d.Designation,
         ApproverFM = fe.EmpName,
    
     }).ToList();