I have the following query on Entity Framework Core:
public class Question {
public DateTime? Approved { get; set; }
public DateTime Created { get; set; }
}
public class QuestionModel {
public TimeSpan ResponseTime { get; set; }
}
List<Question> questions = await context.Questions
.Select(x =>
new QuestionModel {
ResponseTime = x.Approved.Value - x.Created
}).ToListAsync();
But I get the following error:
System.Data.SqlClient.SqlException: Operand data type datetime2 is invalid for subtract operator.
How can I get a DateTime difference with Entity Framework Core?
You can use too this extension method Subtract()
List<Question> questions = (await context.Questions.ToListAsync())
.Select(x => new QuestionModel {
ResponseTime = x.Approved.Value.Subtract(x.Created);
})
.ToList();