简体   繁体   English

在实体框架的通用存储库中为 get 方法创建按参数分组

[英]Creating a group by parameter for the get method in a generic repository for entity framework

I am using the repository pattern with Entity Framework as described in this article: repository pattern with Entity Framework In the part where the GenericRepository is described ( Generic Repository ) there is a method which is used to get entities from the database set called Get.我正在使用实体框架的存储库模式,如本文所述: 实体框架的存储库模式在描述 GenericRepository 的部分( 通用存储库)中,有一种方法用于从名为 Get 的数据库集中获取实体。 It has an orderBy but no groupBy.它有一个 orderBy 但没有 groupBy。 I am wondering how one might implement a groupBy in the same manner as the orderBy so that you can specify which field to group by dynamically on the entity.我想知道如何以与 orderBy 相同的方式实现 groupBy,以便您可以指定在实体上动态分组的字段。

What I have come up with is this:我想出的是:

Func<IQueryable<TEntity>, IGrouping<string, TEntity>> groupBy = null

and then in the method code it should be used something like this:然后在方法代码中应该使用这样的东西:

if(groupBy != null)
{
    query = groupBy(query).ToList();
}

But this is not compiling since the IGrouping is not queryable.但这不是编译,因为 IGrouping 不可查询。 Does someone know how to point me in the right direction or has a solution to this?有人知道如何指出正确的方向或对此有解决方案吗?

Edit: The reason for doing this instead of using groupby on the returned list is for performance reasons.编辑:这样做而不是在返回列表中使用 groupby 的原因是出于性能原因。 I want the groupby to be sent as an sql statement to the database and resolved there.我希望将 groupby 作为 sql 语句发送到数据库并在那里解析。

Grouping has no sense without projection.没有投影,分组就没有意义。 So you have to define new method which returns IEnumerable with new type.因此,您必须定义新方法,该方法返回具有新类型的IEnumerable

I have added sample of such method.我已经添加了这种方法的示例。 Also removed includeProperties because EF Core ignores Includes during grouping.还删除了includeProperties ,因为 EF Core 在分组期间忽略了 Includes。

Usage sample:使用示例:

_orderRepostory
   .GetGrouped(e => e.UserId, g => new { UserId = g.Key, Count = g.Count()});

And implementation:和实施:

 public class GenericRepository<TEntity> where TEntity : class
 {
    ... // other code

    public virtual IEnumerable<TResult> GetGrouped<TKey, TResult>(
        Expression<Func<TEntity, TKey>> groupingKey,
        Expression<Func<IGrouping<TKey, TEntity>, TResult>> resultSelector,
        Expression<Func<TEntity, bool>>? filter = null)
    {
        var query = dbSet.AsQueryable();

        if (filter != null)
        {
            query = query.Where(filter);
        }

        return query.GroupBy(groupingKey).Select(resultSelector);
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM