You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF版本高于6时,日期相减触发DbArithmeticExpression类型错误求助

解决EF版本高于6时的DbArithmeticExpression错误

问题原因

你写的LINQ查询里,(dateee - q.GotFriendListDate.Value).Days > 30这种.NET日期相减取天数的操作,EF无法将其正确转换为SQL语句,导致抛出DbArithmeticExpression arguments must have a numeric common type错误。

修复方案

不要直接在查询里计算日期差值,而是把条件转换成日期比较的形式,EF能完美解析这种逻辑:

var cutoffDate = DateTime.Now.AddDays(-30); // 直接算出30天前的日期

List<Account> account = webUOW.RepoOf<Account>()
            .Get(q => q.Active == true && 
                      q.GotFriendListDate != null &&  
                      q.GotFriendListDate.Value < cutoffDate)
            .ToList();

或者如果是EF Core环境,也可以用EF内置的日期差函数:

var dateee = DateTime.Now.AddDays(30);

List<Account> account = webUOW.RepoOf<Account>()
            .Get(q => q.Active == true && 
                      q.GotFriendListDate != null &&  
                      EF.Functions.DateDiffDay(q.GotFriendListDate.Value, dateee) > 30)
            .ToList();

注意事项

  • 优先用日期比较的方式,兼容性更好,还能利用数据库日期字段的索引提升性能
  • 使用EF.Functions时,要确保项目引用了对应版本的EF Core包

内容的提问来源于stack exchange,提问作者Kinnan Nawaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:47:00