Skip to main content
 首页 » 编程设计

c#之Linq 在组内查询 2 个日期之间的数据

2024年02月06日11lhb25

我正在尝试使用 Linq 查询我的 MS SQL 数据库。代码是

var ids = (from o in _visitDetail 
                   group o by o.CompanyId into grouped 
                   where (grouped.Max(s => s.DateTime) - grouped.Min(s => s.DateTime)).TotalDays > 0 
                   select grouped); 

这会导致抛出异常:

"DbArithmeticExpression arguments must have a numeric common type."

我假设它认为类型不同,所以我需要将它们转换为 DateTime,这样对于 Linq 来说就非常清楚了。

var ids = (from o in _visitDetail 
                   group o by o.CompanyId into grouped 
                   where (grouped.Max(s => Convert.ToDateTime(s.DateTime)) - grouped.Min(s => Convert.ToDateTime(s.DateTime))).TotalDays > 0 
                   select grouped); 

另一个异常(exception):

"LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.DateTime)' method, and this method cannot be translated into a store expression."

我需要做什么才能在这些范围之间进行查询?

请您参考如下方法:

在 EF 中不支持对日期和时间执行算术运算。 EntityFramework 无法将您的代码转换为 SQL。您可以使用 EntityFunctions.DiffDays( startExpression, endExpression) 方法代替它:

var ids = from o in _visitDetail 
          group o by o.CompanyId into grouped 
          where (EntityFunctions.DiffDays(grouped.Min(s => s.DateTime), grouped.Max(s => s.DateTime))) > 0 
          select grouped; 

附加信息:

EntityFunctions方法称为规范函数。这些是一组功能,所有 Entity Framework 提供程序都支持这些功能。这些规范函数将被转换为提供者的相应数据源功能。规范函数是访问核心语言之外的功能的首选方式,因为它们使查询保持可移植性。

您可以找到所有规范函数 here和所有日期和时间规范函数 here .

不要忘记添加对 System.Data.Objects 和 System.Data.Entity 的引用。