它编译正常但是当我尝试迭代LINQ查询的结果时,我有这样的异常The group by operation contains an expression that cannot be translated
查询是
var query0 = from c in dc.Prices
where Convert.ToDateTime(c.data).CompareTo(left) >= 0
&& Convert.ToDateTime(c.data).CompareTo(right) <= 0
&& c.idsticker.Equals(x)
group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
into groupMonthAvg
select new
{
years = groupMonthAvg.Key.Year,
months = groupMonthAvg.Key.Month,
prices = groupMonthAvg.Average(i => i.value)
};
group by
函数中的哪个表达式错误?
答案 0 :(得分:3)
试试这个:
var query0 = from c in dc.Prices
let date = Convert.ToDateTime(c.data)
where date.CompareTo(left) >= 0 && date.CompareTo(right) <= 0 && c.idsticker.Equals(x)
group c by new { date.Year, date.Month } into groupMonthAvg
select new
{
years = groupMonthAvg.Key.Year,
months = groupMonthAvg.Key.Month,
prices = groupMonthAvg.Average(i => i.value)
};
答案 1 :(得分:1)
我猜这是因为data
中的Price
列是字符串或DateTime
以外的其他类型。
尝试将(DateTime)c.data)
强制转换为Convert.ToDateTime(c.data)
。
我不确定Linq-SQL转换器是否支持强制转换。
如果可能,请将数据库中的基础数据类型更改为DateTime
,如果它存储日期时间值。