将Func传递给Linq到实体Sum(..)

时间:2016-12-21 12:11:15

标签: c# entity-framework linq entity-framework-6 linq-to-entities

我正在尝试创建一个方法,我将实体分组在几个字段上,然后获取另一个字段。像这样:

$container['phpErrorHandler'] = function ($c) { 
    return function ($request, $response, $exception) use ($c) { 
        //Format of exception to return 
        $data = [ 
            'message' => "hello" 
        ]; 
        return $container->get('response')->withStatus($response->getStatus()) 
            ->withHeader('Content-Type', 'application/json') 
            ->write(json_encode($data)); 
    }; 
};

我称之为 private async Task<List<KpiGrounping<int>>> GetGrouping(IQueryable<MyEntityType> query, Func<MyEntityType, int> selector) { return await (from item in entity group itemby new { item.DimCountry.Geo, item.DimPlatform.Platform } into x select new MyGrounpingDto { Geo = x.Key.Geo.Trim(), Platform = x.Key.Platform.Trim(), Value = x.Sum(selector) }).ToListAsync(); }

当我这样做时,我收到错误:&#34;内部.NET Framework数据提供程序错误1025。&#34;抛出 - 我可以毫无意义。

我也发现如果我没有传入选择器,而是直接调用sum,就像var foo = GetGrouping(context.MyEntities, x=>x.MyValue);那样它可以正常工作

1 个答案:

答案 0 :(得分:2)

你有没有试过这样做:

private async Task<List<KpiGrounping<int>>> GetGrouping(IQueryable<MyEntityType> query, Expression<Func<MyEntityType, int>> selector)
    {
        return await (from item in entity
              group itemby new
              {
                  Geo = item.DimCountry.Geo.Trim(),
                  Platform = item.DimPlatform.Platform.Trim()
              } into x
              select new MyGrounpingDto
              {
                  Geo = x.Key.Geo,
                  Platform = x.Key.Platform,
                  Value = x.Sum(selector)
              }).ToListAsync();
}