Home > Net >  Passing value from Nullable Date Time to Date Time variable in Crystal Report
Passing value from Nullable Date Time to Date Time variable in Crystal Report

Time:01-05

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?

CodePudding user response:

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();

CodePudding user response:

Seconding Mamink's answer. Either your second property needs to be:

public DateTime? ApprovedDateDM { get; set; }

OR you need to explicitly check for and cast to null, something like:

if(pa?.Approved_Date is not null)
{
    ApprovedDateDM = (DateTime)pa.Approved_Date, //Error
}

CodePudding user response:

public DateTime? ApprovedDateDM { get; set; }

maybe your model should be like this

-- I know I should comment it but my reputation is less than 50

  •  Tags:  
  • Related