views:

43

answers:

2

I am considering refactoring a repository I have to improve its flexibility and reduce the method count.

Where there are the following methods:

Collection GetAllUsersByRole(Role role)
User GetUserByuserName(string userName)

...I would like to have a single method taking a Linq expression:

ICollection GetUsers(Expression e)
{
  //retrieve user collection from store
  //apply expression to collection and return
}

Is this a reasonable approach? Presumably I'd lose some efficiency because the full users collection would need to be retrieved and filtered every time, rather than retrieving a subset of users according to some hard-coded criteria?

Edit: NHibernate provides ORM in my implementation.

+3  A: 

You really want to take an Expression as the argument to that method.

As far as performance, it really comes down to how far you want to go with it. The simplest method is bringing all the objects into memory and then filtering with the predicate expression.

On the other hand, you mention some sort of criteria. I have no idea what your back end data system is, but you can take these passed filters and transform them into your criteria. This is essentially what Linq to SQL and Linq to Entities does, but hopefully the range of possibilities you need to support is significantly smaller. If not, it might make sense to switch to one of the ORM tools if you want to take this approach.

Chris
"The simplest method is bringing all the objects into memory and then filtering with the predicate expression." Thats a great point, this class can just be a translator to the other logic, but makes the number of exposed methods smaller.
NickLarsen
+1  A: 

This is not a very reasonable approach, cos typically will cost you a lot of performance issues. If you use data access technology that accepts LINQ queries than you just can use this query (expression) with it. This can be IQueryable for LINQ to SQL or ObjectQuery for EntityFramework. It also can be ICriteria (without linq support) for nHibernate. All modern ORM tools have its own expression API, so you just need to use it. If you have custom Data Access layer you will need to write your own API for creating criterias, for example Query Object.

Restuta
We use NHibernate, so I should supply an ICriteria object instead of an expression? If so, I'd be disappointed not be able to use lambda expressions.
Ben Aston
@Ben Aston, NHibernate has a start at creating a full featured Linq provider (http://sourceforge.net/projects/nhibernate/files/), but I do not know what the current level of support is. As I mentioned in my response, you can transform the filter expression into Hibernate Criteria, but you may want to restrict the kinds of queries you can run this way (Simple equality of a property to a constant would likely be easy, for example).
Chris