LINQ查询NotSupportedException OrderBy TimeSpan的平均值

时间:2015-01-05 04:42:14

标签: linq sql-order-by average timespan

var seasonPlayer = (from SeasonPlayer in db.SeasonPlayerSet 
                    orderby SeasonPlayer.StatisticsPlayer.Average(x => x.STP_timeplay.Ticks) descending 
                    select SeasonPlayer).ToList();

SeasonPlayer有一个ICollection of StatisticsPlayer所以我想得到一个平均花费在法庭上的时间,这个时间是由STP_timeplay下降的,这是一种典型的TimeSpan。我无法通过STP_timeplay获得平均值,因为它不是小数,所以我尝试通过Ticks获得平均值。它引发了一个例外:

The specified type member 'Ticks' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

2 个答案:

答案 0 :(得分:1)

试试这个: -

var seasonPlayer = db.SeasonPlayerSet.ToList()
                     .OrderByDescending(x => x.StatisticsPlayer
                                             .Average(z => z.STP_timeplay.Ticks);

答案 1 :(得分:1)

问题是Linq to Entities查询提供程序无法将您的LINQ转换为连接到统计播放器的Sql查询,平均时间播放,按季节播放器分组。

鉴于您似乎正在迭代所有季节玩家,如果记录数量不是太大,您可以将这一切全部记入内存:

var seasonPlayer = db.SeasonPlayerSet
                      .Include(sp => sp.StatisticsPlayer)
                      .ToList()
                      .Select(sp => new {SeasonPlayer = sp, Average = sp.StatisticsPlayer.Average(stp => stp.STP_timeplay.Ticks)})
                      .OrderByDescending(sp => sp.Average)
                      .Select(sp => SeasonPlayer)
                      .ToList();