I’m implementing the service \ repository pattern in a new project. I’ve got a base interface that looks like this. Everything works great until I need to use the GetMany method. I’m just not sure how to pass a LINQ expression into the GetMany method. For example how would I simply sort a list of objects of type name?
nameRepository.GetMany( ? )
public interface IRepository<T> where T : class
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Expression<Func<T, bool>> where);
T GetById(long Id);
T GetById(string Id);
T Get(Expression<Func<T, bool>> where);
IEnumerable<T> GetAll();
IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
Assuming that you had an implementation of
IRepository<MyClass>, you would make a call toGetManylike so:Note the
mc => truelambda expression.mcin this case is the parameter (in this case, of typeMyClass) passed to theExpression<Func<T, bool>>which will be evaluated (one would assume through anIQueryable<T>) and themc.SomeProperty == someValueis an expression which returnstrue, which is the second type parameter of theExpression<Func<T, bool>>.Once you have the
filtered, you can use theorder byclause (or theOrderByextension method, they’re the same) to sort the results, like so:Note that
GetManyreturns anIEnumerable<T>, not anIQueryable<T>; this is important if your result set is large, as the ordering will happen on the client, and not be sent to the server.For an
OrderByoperation, this can be expensive because it has to go through the entire sequence (to order) before returning the first result.