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



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

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(,如果我想向这个控制器添加另一个类我应该怎么做?我想有多个类来连接它们,但在我的控制器的构造函数中,我只能使用一个类,问题在哪里?

更新:

添加此wapper类

class TransactionManager
{
CentralEntities _ctx;
Hashtable _repositories;
public TransactionManager(CentralEntities ctx)
{
_ctx = ctx;
}
public RepositoryTest<T> CreateRepository<T>() where T : class
{
if (_repositories == null)
_repositories = new Hashtable();
var type = typeof(T).Name;
if (!_repositories.Contains(type))
{
var repositoryType = typeof(RepositoryTest<>);
var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(T)), _ctx);
_repositories.Add(type,repositoryInstance);
}
return (RepositoryTest<T>)_repositories[type];
}
public int Save()
{
return _ctx.Save();
}
}

现在在控制器中

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();
}

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

https://github.com/AJEETX/RepositoryPattern

相关内容

最新更新