Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should repositories implement IQueryable<T>?

I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable.

Like this:

public interface IRepository<T> : IQueryable<T> {     T Save(T entity);     void Delete(T entity); } 

Or this:

public interface IRepository<T> {     T Save(T entity);     void Delete(T entity);     IQueryable<T> Query(); } 

LINQ usage would be:

from dos in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>() where dos.Id == id select dos 

Or...

from dos in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>().Query where dos.Id == id select dos 

I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories?

like image 748
Andy S Avatar asked Oct 02 '08 20:10

Andy S


People also ask

Should I return IQueryable from repository?

If you are using repository pattern - no, you should not return IQueryable.

When should I use IQueryable?

IQueryable uses Expression objects that result in the query being executed only when the application requests an enumeration. Use IQueryable when you have to run ad-hoc queries against data source like LinQ to SQL Server,Entity framework and other sources which implement IQueryable.

Should I repository return list or IEnumerable?

It depends on whether you wish to have any future queries performed on the entity and whether these should be in memory or not: If there are to be future queries and the DB should do the work return IQueryable. If there are to be future queries and it is to be done in memory return IEnumerable.

Does IEnumerable implement IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.


1 Answers

Depends on if you want a Has-A or an Is-A relationship.

The first one is an Is-A relationship. The IRepository interface is a IQueryable interface. The second is a has-a. The IRepository has an IQueryable interface. In the process of writing this, I actually like the second better then the first, simply because when use your second IRepository, I can give the Query() method ANYTHING that returns IQueryable. To me, that is more flexible then the first implementation.

like image 79
MagicKat Avatar answered Oct 17 '22 00:10

MagicKat