如何在存储库模式(MVC)中具有多个类

时间:2018-07-24 14:39:17

标签: c# model-view-controller repository-pattern

对存储库模式有些困惑,在这里我编写代码然后解释:

 public  interface IRepositoryTest<T> where T:class
{
  IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate);

}

这是上述签名的实现:

 public class RepositoryTest<T>:IRepositoryTest<T> where T:class
{

    private CentralEntities db = null;
    private DbSet<T> table = null;

    public RepositoryTest() {
    this.db = new CentralEntities();
    table = db.Set<T>();
                        }

    public RepositoryTest(CentralEntities db)
    {

        this.db = db;
        table = db.Set<T>();
    }


    public IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate)
    {

        return table.Where(predicate).ToList();

    }

}

现在在我的控制器中,如果我想使用此存储库,则必须执行以下操作:

  IRepositoryTest<UserRoles> _repository = null;

    public DashbrdController(IRepositoryTest<UserRoles> _repository)
    {

        this._repository = _repository;


    }

    public DashbrdController()
    {

        this._repository = new RepositoryTest<UserRoles>();

    }

    public ActionResult DashBrd()
    {

        var rslt = _repository.SelectAll(s=>s.user_id=="myName");         
        return View();

    }

这里的问题是,在我的控制器中,我只能使用模型中的一个类,如您所看到的(UserRoles),如果我想向该控制器中添加另一个类,我该怎么做?我想拥有多个类加入它们,但是在我的控制器的构造函数中,我只能使用一个类,问题出在哪里?

1 个答案:

答案 0 :(得分:2)

已更新:

添加此包装类

public class DashbrdController:Controller
{ 
 TransactionManager _tMgr;
public DashbrdController(TransactionManager tMgr)
{
    this._tMgr=tMgr;
}

public DashbrdController()
{
    this._tMgr=new TransactionManager() ;
}

public ActionResult DashBrd()
{
    var rslt = _tMgr.CreateRepository<UserRoles>().SelectAll(s=>s.user_id=="myName");         
    return View();
}
public ActionResult AnotherDashBrd()
{
    var anotherrslt = _tMgr.CreateRepository<AnotherRoles>().SelectAll(s=>s.Name=="myName");         
    return View();
}

现在在控制器中

View.GONE

此外,您可以使用有关存储库模式的源代码检查项目

https://github.com/AJEETX/RepositoryPattern