自定义存储库设计类中的功能

时间:2016-04-20 09:33:15

标签: c# asp.net-mvc asp.net-mvc-4 entity-framework-6 repository-pattern

我认为事情会起作用的方式可能是错的 但我真的很困惑,因为我第一次使用存储库设计模式。 问题是存储库类只有

GetaLL(),GetALLByID(),Update()或Save()。

但是如果我需要提取记录,以便我在一个表中有groupofUsers 为此我需要计算每个组中有多少用户。用户表是一个不同的表。

该关系可以假设为“UserGroup”作为具有唯一的父表 usergroups,但是这个UserGroup表有一个键,它将是外键 另一个表“用户”。组中可能有许多用户,并且与此类似 我需要找出同一个表下有多少个角色,即“UserGroup”。 这是另一个表“角色”,它将以与“UserGroups”相同的方式拥有“UserGroups” 它在“用户”表中。

以下是我如何获取记录。我的存储库只有

 public abstract class Repository<T>
        where T : class
    {
        private readonly IDbSet<T> _dbset;

    public virtual IQueryable<T> GetAll()
        {
            return this._dbset;
        }
}

在控制器中,我将其称为:

private readonly Repository<UserGroup> _GroupRepository;

    public IEnumerable<UserGroupModel> GetListedGroups()
        {
            var list = this._GroupRepository.GetAll();

        }

1 个答案:

答案 0 :(得分:0)

您可以拥有一个派生自Repository<T>的新类,并在其中添加新方法。

public class UserGroupRepository : Repository<UserGroup>
{
    public UserCountInGroups GetUserCountInGroup()
    {
        // Do something with this._dbset here.
    }
}

因此,在控制器中,您使用UserGroupRepository代替Repository<UserGroup>

private readonly UserGroupRepository _GroupRepository;

public IEnumerable<UserGroupModel> GetListedGroups()
{
    var list = this._GroupRepository.GetAll();
    var userCount = this._GroupRepository.GetUserCountInGroup();
    // Do something here.
}