Expose a repository as an IQueryable

前端 未结 5 1882
梦如初夏
梦如初夏 2021-01-21 20:58

I\'d like to expose a Repository as an \'IQueryable\' type.

The repository uses Linq to NHibernate to communicate with the database.

Can anyone point me at an ex

5条回答
  •  生来不讨喜
    2021-01-21 21:35

    I can see two possible solutions here:

    1. Expose IEnumerable and use .AsQueryable() when needed

      // Repository
      public IEnumerable GetAll() {
          return _dbContext.People.AsQueryable();
      }
      
      // Usage
      public Person GetByPhone(string phoneNumber) {
          var queryablePeople = _personRepository.GetAll().AsQueryable();
          return queryablePeople.FirstOrDefault(perspn => person.Phone == phoneNumber);
      }
      
    2. Accept expression in Repository method

      // Repository
      public IEnumerable GetPeople(Expression> filter) {
          return _dbContext.People.Where(filter);
      }
      
      // Usage
      public Person GetByPhone(string phoneNumber) {
          return _personRepository.GetPeople(person => person.Phone == phoneNumber).FirstOrDefault();
      }
      

    Note: Not any expression filter can be translated to SQL Query by Entity Framework

提交回复
热议问题