开发者

linq to nhibernate reusing business logic in queries

开发者 https://www.devze.com 2023-04-03 08:01 出处:网络
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:

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开发者_Python百科 to repeatedly use across a project.

Thanks in advance for any help.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号