LINQ to Entities不识别方法 [英] LINQ to Entities does not recognize the method

查看:110
本文介绍了LINQ to Entities不识别方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的代码:

  var queryResult = result.Where(x => x.FollowedUp.Value.GetWeekFromDateTime()
== DateTime.Now.GetWeekFromDateTime())。选择(x => x);






我的扩展方法是:

  public static int GetWeekFromDateTime(this DateTime date)
{
return System.Threading.Thread.CurrentThread.CurrentCulture.Calendar .GetWeekOfYear(date,CalendarWeekRule.FirstFourDayWeek,DayOfWeek.Monday);
}






问题:



我得到LINQ to Entities不认识GetWeekFromDateTime的方法,我明白为什么因为它试图将我的代码翻译成sql代码,而GetWeekFromDateTime不存在。但是我该怎么办?我想比较我从我的数据库到这个周数的日期的周数。



谢谢!

解决方案

如果您在 FollowedUp 字段上有一个体面的索引,您可能需要在这里调整您的算法,而不是仅仅通过C#计算最小和最大日期是当前星期,并将您的查询作为值> = min&&&值<= max 。这样你就不会对数据库的每一行进行计算。






但是更直接地回答你的问题即使我不建议您在特定情况下这样做:您可以创建一个SQL函数,在此进行计算,将其导入到数据上下文中,并将其调用到查询内。



请注意,这将导致每一行都通过该函数。此外,即使你仍然想这样做,你应该改变你如何获得当前的一周;您只需要获得该值一次,并在查询中使用一个变量...不需要尝试为每一行重新计算它。


I have a problem with Linq to Entities that I can't find a workaround for.

This is my code :

var queryResult = result.Where(x => x.FollowedUp.Value.GetWeekFromDateTime() 
    ==  DateTime.Now.GetWeekFromDateTime()).Select(x => x);


and my extention method is :

    public static int GetWeekFromDateTime(this DateTime date)
    {
        return System.Threading.Thread.CurrentThread.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    }


Problem :

I am getting "LINQ to Entities does not recognize the method GetWeekFromDateTime" and I understand why because it's trying to translate my code into sql code and of "GetWeekFromDateTime" does not exist. But how do I do it? I want to compare the weeknumber from date that I get from my database to this weeknumber.

Thank you!

解决方案

If you have a decent index on the FollowedUp field, you might want to adjust your algo here to instead just calculate via C# what the Min and Max dates are for the current week, and do your query as a value >= min && value <= max instead. That way you aren't doing a calculation on every single row of the database.


But to answer your question more directly, even if I don't recommend doing it this way in your particular case: You could create an SQL function which does the calculation here, import it to your data context, and call it inside your query instead.

This would result in every row going through that function, keep in mind. Also, even if you still want to do it this way, you should change how you get getting the current week, too; You only need to get that value once, and use a variable for it in the query... no need to try to recalculate it for every row.

这篇关于LINQ to Entities不识别方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆