Linq静态方法错误

时间:2011-04-01 16:41:41

标签: linq linq-to-sql

我创建了以下函数来获取日期差异:

    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)'方法,并且此方法无法转换为商店表达式。

请建议解决方案

3 个答案:

答案 0 :(得分:1)

MonthsDifference函数无法映射到SQL,这就是您收到此错误的原因。您需要重写查询表达式而不需要调用自己的方法来执行您想要的操作(这可能是不可能的 - 我不确切知道LINQ to Sql支持哪些本机数据库函数), 获取结果集并在本地进行过滤。

后一种方法会是这样的:

var count = context.AccountOwners.ToArray()
       .Count(o => MonthsDifference(p.Account.StateChangeDate,DateTime.Now) < 4);

答案 1 :(得分:1)

如果要在Linq中执行此操作,则需要内联此方法,以便Linq2Sql可以将其转换为sql。

所以我认为你需要这样的东西:

var start = DateTime.Now;
var query = from c in context.AccountOwners
            let accountDate = c.Account.StateChangeDate
            let diff = (start.Month + start.Year * 12) - (accountDate.Month + accountDate.Year * 12) + ...
            where diff < 4
            select c;

return query.Count();

Months difference between dates

相关联

答案 2 :(得分:1)

在LINQ to Entities中,您可以使用Entity functions

using System.Data.Objects;

var query = from c in context.AccountOwners.Where(EntityFunctions.DiffMonths(
                           p.Account.StateChangeDate,DateTime.Now) < 4 )
            select c;
return query.Count();