Entity Framework Core中的DateTime差異

entity-framework-core

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

但是我收到以下錯誤:

System.Data.SqlClient.SqlException: Operand data type datetime2 is invalid for subtract operator.

如何獲得與Entity Framework Core的DateTime差異?

熱門答案

你也可以使用這個擴展方法Subtract()

List<Question> questions = (await context.Questions.ToListAsync())
.Select(x => new QuestionModel {
ResponseTime = x.Approved.Value.Subtract(x.Created);
})
.ToList();


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因