Entity framework core 实体框架核心中的日期时间差

Entity framework core 实体框架核心中的日期时间差,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.Qu

我对实体框架核心有以下疑问:

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();
如何使用Entity Framework Core获得日期时间差

System.Data.SqlClient.SqlException:操作数数据类型datetime2对于减法运算符无效

datetime2
表明它正在尝试转换为SQL语句。因此,您应该尝试在内存中执行此操作(客户端,而不是SQL Server端)

List questions=(等待context.questions.toListSync())
.选择(x=>
新问题模型{
ResponseTime=x.Approved.Value-x.Created
}).ToList();
通过在select操作之前调用
toListSync()
,可以强制执行查询。然后你会把所有的问题都记在记忆里。当您现在对其执行
。选择
,它将在内存中执行,而不会尝试转换为SQL查询

System.Data.SqlClient.SqlException:操作数数据类型datetime2对于减法运算符无效

datetime2
表明它正在尝试转换为SQL语句。因此,您应该尝试在内存中执行此操作(客户端,而不是SQL Server端)

List questions=(等待context.questions.toListSync())
.选择(x=>
新问题模型{
ResponseTime=x.Approved.Value-x.Created
}).ToList();

通过在select操作之前调用
toListSync()
,可以强制执行查询。然后你会把所有的问题都记在记忆里。当您现在对其执行
。选择
,它将在内存中执行,而不会尝试转换为SQL查询。

您也可以使用此扩展方法Subtract()

List questions=(等待context.questions.toListSync())
.选择(x=>new QuestionModel{
响应时间=x.已批准的值.减去(x.已创建);
})
.ToList();

您也可以使用此扩展方法Subtract()

List questions=(等待context.questions.toListSync())
.选择(x=>new QuestionModel{
响应时间=x.已批准的值.减去(x.已创建);
})
.ToList();
System.Data.SqlClient.SqlException: Operand data type datetime2 is invalid for subtract operator.
List<Question> questions = (await context.Questions.ToListAsync())
.Select(x => new QuestionModel {
ResponseTime = x.Approved.Value.Subtract(x.Created);
})
.ToList();