Linq静态方法错误
我创建了以下函数来获取日期差异:
public static double MonthsDifference(DateTime dtStart, DateTime dtNow)
{
DateTime start = dtStart;
DateTime end = dtNow;
int compMonth = (end.Month + end.Year * 12) - (start.Month + start.Year * 12);
double daysInEndMonth = (end - end.AddMonths(1)).Days;
double months = compMonth + (start.Day - end.Day) / daysInEndMonth;
return months;
}
我在 LINQ 查询中使用它
var query = from c in context.AccountOwners.Where( MonthsDifference(p.Account.StateChangeDate,DateTime.Now) < 4 )
select c;
return query.Count();
,但它给出错误:
LINQ to Entities 无法识别方法 'Double MonthsDifference(System.DateTime, System.DateTime)' 方法,并且此方法无法转换为存储表达式。
请建议解决方案
I have created following function to get dates difference:
public static double MonthsDifference(DateTime dtStart, DateTime dtNow)
{
DateTime start = dtStart;
DateTime end = dtNow;
int compMonth = (end.Month + end.Year * 12) - (start.Month + start.Year * 12);
double daysInEndMonth = (end - end.AddMonths(1)).Days;
double months = compMonth + (start.Day - end.Day) / daysInEndMonth;
return months;
}
I am using it in my LINQ query
var query = from c in context.AccountOwners.Where( MonthsDifference(p.Account.StateChangeDate,DateTime.Now) < 4 )
select c;
return query.Count();
but it is giving error:
LINQ to Entities does not recognize the method 'Double MonthsDifference(System.DateTime, System.DateTime)' method, and this method cannot be translated into a store expression.
Please suggest solution
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想在 Linq 中执行此操作,则需要内联此方法,以便 Linq2Sql 可以将其转换为 sql。
所以我认为你需要类似的东西:
链接到日期之间的月差
If you want to do this in the Linq then you need to inline this method so that Linq2Sql can translate it into sql.
So I think you'll need something like:
Linked to Months difference between dates
在 LINQ to Entities 中,您可以使用实体函数 :
In LINQ to Entities you can use Entity functions:
MonthsDifference
函数无法映射到 SQL,这就是您收到此错误的原因。您需要重写查询表达式而不调用您自己的方法来执行您想要的操作(这可能是不可能的 - 我不确切知道 LINQ to Sql 支持哪些本机数据库函数), 或获取结果集并在本地进行过滤。后一种方法将如下所示:
The
MonthsDifference
function cannot be mapped to SQL, which is why you are getting this error. You need to either rewrite the query expression without any calls to your own methods to do what you want (which may be impossible -- I don't know exactly which native database functions LINQ to Sql supports), or fetch the result set and do the filtering locally.The latter approach would go like this: