EF5:LINQ to Entities无法识别方法System.Nullable System.Decimal Median

时间:2013-11-28 19:44:05

标签: c# sql-server linq entity-framework

我首先使用EF5代码。当我执行我的查询时:

var priceIndexQuery = from r in unitOfWork.Repository<StockIndexPriceResult>()
                                      where request.CalculateModel.StockCompanies.Contains(r.StockCompanyId)
                                            && r.StockIndexId == request.CalculateModel.StockIndexId
                                            && r.ResultDate >= dateFiveYearsAgo
                                      orderby r.ResultDate descending
                                      group r by r.ResultDate
                                          into g
                                          select g;

然后:

var query = priceIndexQuery.Select(g => new CalculateAggregateModel
                                                    {
                                                        ResultDate = g.Key,
                                                        Value = g.Median(p => p.Result ?? 0),
                                                        PeriodType = "Day"
                                                    });

                                    resultData = query.ToList();

我对 query.ToList(); 有所了解到目前为止我所知道的是MSSQL无法执行 Median 功能。我有什么方法可以解决它吗?

1 个答案:

答案 0 :(得分:1)

实体框架无法将您的中间方法转换为SQL,因此您需要在执行Median方法之前查询数据库。 在第一次查询后立即尝试执行.ToList().AsEnumerable()

var priceIndexQuery = (from r in unitOfWork.Repository<StockIndexPriceResult>()
                                      where request.CalculateModel.StockCompanies.Contains(r.StockCompanyId)
                                            && r.StockIndexId == request.CalculateModel.StockIndexId
                                            && r.ResultDate >= dateFiveYearsAgo
                                      orderby r.ResultDate descending
                                      group r by r.ResultDate
                                          into g
                                          select g).ToList();