score:3

Accepted answer

we use something very similar. one thing you need to decide on is if you are going to expose iqueryable outside of the repository. your find method returns ienumerable which could be the iqueryable returned from your when clause.

the advantage of returning the iqueryable is that you can further refine your criteria up outside of your repository layer.

repository.find(predicate).where(x => x.somevalue == 1);

the expression will only be compiled when you come to use the returned data and here in lies the disadvantage. because you only hit the database when you actually come to use the results you could end up trying to call the database after your session (nhibernate) or connections have been closed.

my personal preference is to use the specification pattern where you pass your find method an ispecification object is used to do the query.

public interface ispecification<tcandidate>
{
    iqueryable<tcandidate> getsatisfyingelements(iqueryable<tcandidate> source);
}

public class testspecification : ispecification<testentity>
{
    public iqueryable<testentity> getsatisfyingelements(iqueryable<testentity> source)
    {
        return source.where(x => x.somevalue == 2);
    }
}

public class activerecordfoorepository: ifoorepository
{
    ...

    public ienumerable<tentity> find<tentity>(ispecification<tentity> specification) where tentity : class 
    {
        ...

        return specification.getsatisfyingelements(activerecordlinq.asqueryable<tentity>()).toarray();

        ...
    }

    public tentity findfirst<tentity>(ispecification<tentity> specification) where tentity : class 
    {
        return specification.getsatisfyingelements(activerecordlinq.asqueryable<tentity>()).first();
    }
}

after the query is run the repository calls toarray or tolist on the resulting iqueryable returned from the specification so that the query is evaluated there and then. whilst this may seem less flexible than exposing iqueryable it comes with several advantages.

  1. queries are executed straight away and prevents a call to the database being made after sessions have closed.
  2. because your queries are now bundled into specifications they are unit testable.
  3. specifications are reusable meaning you don't have code duplication when trying to run similar queries and any bugs in the queries only need to be fixed in one place.
  4. with the right kind of implementation you can also chain your specifications together.

repository.find(
    firstspecification
        .and(secondspecification)
        .or(thirdspecification)
        .orderby(orderbyspecification));

score:0

is passing a func as a parameter to your service layer's find method, instead of the foosearchargs, an option? enumerables have a where method (linq) that takes a func as a parameter, so you could use it to filter the results.


Related Query