skip to Main Content

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?

2

Answers


  1. 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();
    
    Login or Signup to reply.
  2. You can also use null-coalescing operator (??= or ?? ) which will return the value if it is not null, or return the value to the right of the operator

    If you want to return current datetime in case nullable one is null, you can use the following

    ApprovedDateDM = Approved_Date ?? DateTime.Now

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search