C# – subtract two Dates in Linq to Entities which returns a timespan

centity-frameworklinq-to-entities

I want to subtract two Dates and get the value in Timespan for Example

TimeSpan duration = Convert.ToDateTime(completeDate).Subtract(Convert.ToDateTime(lastRundate));

This is for Normal implementation. HOw can one do it in Linq to Entities in Entity Framework wherein

from job in Jobs
   select new JobEntity
  {                                                  
  Duration =  job.CompleteDate.Value.Subtract(job.NextRunDate.Value)
  };

where Jobs is my table, CompleteDate & NextRunDate are my column names of DataType DateTime? (since it allows null value)
When I tried this code, it gives me this error

LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)' method, and this method cannot be translated into a store expression.
Please do let me know how to go about this.
thanks in advance

Best Answer

Why not extend your JobEntity model?

public DateTime NextRunDate { get; set; }
public DateTime CompletedDate { get; set; }
public Timespan Duration
{
    get
    {
        return CompleteDate.Subtract(NextRunDate)
    }
}