使用c#Func作为IQueryable的一部分而不执行内存调用

我正在尝试构建一个将作为IQueryable而不是在内存(IEnumerable)中对数据库执行的查询.

该查询将用于多个不同的目的,每个目的的计算Total属性的方式略有不同.

因为我使用Func来计算总数,所以我得到一个错误,告诉我sql不知道如何处理我的Func的Invoke方法,这是可以理解的.

为了解决这个问题,我不得不通过调用ToList()来将分组列入memor,这对性能不利.

有没有办法可以将此查询作为IQueryable执行?否则我将不得不用计算差异写20次这个查询

Func<IGrouping<object, MyType>, double?> calculateTotal= (group) => @group.Sum(x => x.PassengerTotal);

Dictionary<object, double?> weekValues = queryable.GroupBy(o => new
               {
                   Year = SqlFunctions.DatePart("yyyy", o.DateCreated),
                   Week = SqlFunctions.DatePart("ww", o.DateCreated),
                   Source = o.SourceId,
               })
               .ToList() //NEED TO REMOVE THIS CALL
               .Select(ac => new WeeklyGraphGroup()
               {
                   Year = ac.Key.Year,
                   Week = ac.Key.Week,
                   SourceId = ac.Key.Source,
                   Total = calculateTotal(ac)
               })
               .ToDictionary(dict =>
                   new
                   {
                       Year = dict.Year,
                       Week = dict.Week,
                       Source = dict.SourceId
                   }, grp => grp.Total);

最佳答案 创建一个分部类,如下所示:

public partial class WeeklyGraphGroup
{
    public int ? Year { get; set; }

    public int  ? Week { get; set; }

    public int Source { get; set; }

}

public partial class WeeklyGraphGroup
{
    private int ? _Total;

    public int ? Total
    {


        get
        {


            this._Total = CalculateTotal(this.Year, this.Week, this.Source);

            return this._Total;
        }

    }

    public int ? CalculateTotal(int ? Year, int ? Week, int Source)
    {

        // do your calculation and return the value of total
        // use whatever formula you want here. I guess you are calculating 
        // total based on any of the parameters(year, week or source);

        return value;

    }



}

然后按以下方式进行查询:

var list = db.Stores.GroupBy(o => new WeeklyGraphGroup
{
Year = SqlFunctions.DatePart("yyyy", o.DateCreated),
Week = SqlFunctions.DatePart("ww", o.DateCreated),
Source = o.SourceId,
})
.Select ( u => new WeeklyGraphGroup 
{
Year = u.Key.Year,
Week = u.Key.Week,
Source = u.Key.Source
}
).ToList();

总计将自动更新

点赞