2013-11-21 58 views
0

我想使用的EntityFramework執行Linq查詢,並得到錯誤LINQ到實體無法識別方法EntityFunctions.DiffMonths

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Nullable`1[System.Int32] DiffMonths(System.Nullable`1[System.DateTime], System.Nullable`1[System.DateTime])' method, and this method cannot be translated into a store expression. 

代碼

public bool FreeConversionExceeded(string ip) 
    { 
     var count = _statisticRepository.GetAll().Count(p => p.Ip == ip && EntityFunctions.DiffMonths(DateTime.UtcNow, p.DateStamp) == 0); 
     return count > 200; 
    } 


public IQueryable<Statistic> GetAll() 
    { 
     return _context.Statistic; 
    } 

我只是不明白爲什麼EntityFunctions.DiffMonths不管用。從幫助文件「This function is translated to a corresponding function in the database.」,所以它應該工作?

+0

無法重現此操作,它使用'DateTime'和'DateTime?'列。 –

+0

我也不明白爲什麼它不起作用。它在我以前的項目中運行良好,我找不到原因! – Tomas

回答

0

我有確切的問題。解決方案發布在這裏LINQ + EntityFunctions in asp.net mvc

問題是你可能引用System.Data.Objects的EntityFunctions。如果您使用的是EntityFramework,請嘗試引用System.Data.Entity.Core.Objects

using System.Data.Entity.Core.Objects; 

btw,EntityFunctions已被棄用。嘗試改用DbFunctions。

using System.Data.Entity; 
... 
... 
... 
public bool FreeConversionExceeded(string ip) 
{ 
    var count = _statisticRepository.GetAll().Count(p => p.Ip == ip && DbFunctions.DiffMonths(DateTime.UtcNow, p.DateStamp) == 0); 
    return count > 200; 
} 

我知道這個答案遲了幾年。 但我希望這篇文章可以幫助有人面臨類似的問題。

歡呼聲

相關問題