Entity framework 在实体框架中计算两个日期之间的平均时间跨度

Entity framework 在实体框架中计算两个日期之间的平均时间跨度,entity-framework,Entity Framework,我有一个包含两列的数据库表:StartDateTime和FinishDateTime。两者都是可为空的日期时间列 我想计算每行两个字段之间的平均时间。即我记录的事件的平均持续时间 我得到了一个“DbarithmetricExpression参数必须有一个数值公共类型。” 示例EF代码对演示进行了简化 from p in new DbContext() where p.user_id = 123 && p.StartDateTime != null && p.Fin

我有一个包含两列的数据库表:
StartDateTime
FinishDateTime
。两者都是可为空的日期时间列

我想计算每行两个字段之间的
平均时间。即我记录的事件的平均持续时间

我得到了一个“DbarithmetricExpression参数必须有一个数值公共类型。”

示例EF代码对演示进行了简化

from p in new DbContext()
where p.user_id = 123
&& p.StartDateTime != null
&& p.FinishDateTime != null
select new {p.StartDateTime, p.FinishDateTime})
.Average(p=> (p.FinishDateTime.Value - p.StartDateTime.Value).Ticks)

我喜欢上面的一个例子,因为SQL让这变得轻而易举。

这取决于您的数据提供商,它可能支持,您可以这样做:

(from p in new DbContext()
where p.user_id = 123
&& p.StartDateTime != null
&& p.FinishDateTime != null
select new {p.StartDateTime, p.FinishDateTime})
.Average(x=> DbFunctions.DiffMilliseconds(p.FinishDateTime,p.StartDateTime))
如果没有,我认为您必须在选择后将linq转到对象:

(from p in new DbContext()
where p.user_id = 123
&& p.StartDateTime != null
&& p.FinishDateTime != null
select new {p.StartDateTime, p.FinishDateTime})
.ToArray()
.Average(x=> (p.FinishDateTime -p.StartDateTime).Ticks)

Average
中的
x
是什么?
x
似乎是打字错误。我边走边编问题代码。对不起,太棒了,我会试一试的。正在尝试确保它是在SQL server端生成的,以避免使用
.ToArray()
或类似命令拉出数据集