LINQ to Entities不支持Convert.ToDateTime方法解決一例

錯誤提示:

LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression.

LINQ to Entities 不识别方法“System.DateTime ToDateTime(System.String)”,因此该方法无法转换为存储表达式。

代碼:

qAReturnAnalyze = qAReturnAnalyze.Where(a => Convert.ToDateTime(a.returnDate) >= beginDate && Convert.ToDateTime(a.returnDate) <= endDate);

原因分析:

因為在數據庫中 a.returnDate 字段是string,beginDate是Datetime類型,

在使用 Convert.ToDateTime 方法解析時出現錯誤,

而字段類型又不能更改,在網上查了很多方法都不行,最后轉換思路,

將beginDate轉換成string,然後使用String的靜態方法.Compare順利通過。

解決方法如下:

qAReturnAnalyze = qAReturnAnalyze.Where(d => String.Compare(d.returnDate, beginDate)>=0 &&String.Compare( d.returnDate, endDate)<=0);
原文地址:https://www.cnblogs.com/keepee/p/8484418.html