使用lambda表达式连接表

时间:2018-02-17 23:30:27

标签: c# lambda repository-pattern

我在MVC中非常新,我在存储库模式中遇到了一个非常大的问题,是否有人可以帮助我如何在存储库模式中的两个表之间加入和分组?这里是代码:

 public class GenericTestRepository<TEntity> where TEntity:class
{

internal CentralEntities context;
internal DbSet<TEntity> dbSet;


public GenericTestRepository(LTWCentralEntities context )
{
    this.context = context;
    this.dbSet = context.Set<TEntity>();
}


public virtual IEnumerable<TEntity> Get(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    string includeProperties = "")
{
    IQueryable<TEntity> query = dbSet;

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

    foreach (var includeProperty in includeProperties.Split
        (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    if (orderBy != null)
    {
        return orderBy(query).ToList();
    }
    else
    {
        return query.ToList();
    }
 }


}

这是我的UnitOfWork:

   private CentralEntities context = new CentralEntities();
   private GenericRepositoryTest<User> usrRepo;
   private GenericRepositoryTest<MasterData> mastrData;

   public GenericRepositoryTest<User> UserRepo
  {
     get
     {
         return this.usrRepo ?? new GenericRepositoryTest<User>(context);
      }
  }

   public GenericRepositoryTest<MasterData> MastrData
   {
     get
     {
       return this.MastrData ?? new GenericRepositoryTest<MasterData>
 (context);
     }
 }

在我的控制中,我想加入这两个表,但我不知道如何,如果没有存储库和工作单元模式,我将执行以下操作:

 private CentralEntities DB = new CentralEntities();
    var listOfParks = (from s in DB.MasterDatas
                       join t in DB.Users1
                       on s.pv_person_resp_id equals t.user_id                                                           
                       select new SelectListItem
                       {
                           Text = t.user_name
                       }).Distinct().OrderBy(m=>m.Text).ToList();

我的控制员:

UnitOfWorkForTest _unitofWork=new UnitOfWorkForTest ();

但是现在我有了存储库和工作单元,我应该如何使用lambda表达式进行连接并使用我的存储库和unitofwork?谢谢

1 个答案:

答案 0 :(得分:1)

UnitOfWork更改为

之后
public GenericRepositoryTest<MasterData> MastrData
{
   get
    {
      return this.mastrData ?? new GenericRepositoryTest<MasterData>(context);
    }
}

GenericRepositoryTest班级

上添加以下方法
public IQueryable<TEntity> GetAll()
{
    return _dbSet;
}

最后在你的控制器上:

UnitOfWorkForTest _unitofWork=new UnitOfWorkForTest ();

 var listOfParks = (from s in _unitofWork.MastrData.GetAll()
                   join t in _unitofWork.UserRepo.GetAll()
                   on s.pv_person_resp_id equals t.user_id                                                           
                   select new SelectListItem
                   {
                       Text = t.user_name
                   }).Distinct().OrderBy(m=>m.Text).ToList();

我希望这对你有所帮助!