2

I'm working on a project where we are using fluent nhibernate and perform queries on our repository for entities. Often we write queries like this:

(from person in repository.Query<Person>()
where person.Age > 18 
where person.Age < 50
select person).Single();

Obviously we have some logic here and we would like to be able to encapsulate it somewhere more sensible. An ideal solution would be to do this:

(from person in repository.Query<Person>()
where personIsTheRightAge(person)
select person).Single();

bool personIsTheRightAge(Person person)
{
    return person.Age > 18 && person.Age < 50;
}

But nhibernate doesn't know how to deal with this.

We could provide extension methods to IQueryable< Person> but that won't work if I'm querying a Car entity that has a driver Person and I need to reuse that same logic.

I'm just wondering if anyone has some nice ideas about how to solve this problem in a way that is easy to repeatedly use across a project.

Thanks in advance for any help.

user663470
  • 149
  • 7

1 Answers1

0

You may use something like DDD Specification to encapsulate 'right age' logic:

usersRepository.FindByAgeSpec(RightAgeSpecification rightAge);

and

Boolean isRightAge = car.Driver.IsSatisfiedBy(rightAge);

You might also find it interesting to look at how repositories are implemented in DDD.

Community
  • 1
  • 1
Dmitry
  • 17,078
  • 2
  • 44
  • 70