Question

Please forgive me if I am somewhat unclear, I am just getting started with NHibernate/LINQ/Lambda expressions, and I am actually unsure of what to look for...

I've been working with .NET 2.0 for the past 4 or 5 years and had no opportunity to evolve other than by myself, which is why I am now getting to learn new tech :)

I've been reading alot of blogs and posts and started a personal little project where I try to use the Repository pattern as well as possible.

I am now in the following situation:

  • MyProject.Core.dll: I have this core assembly that contains all the business logic and sets the IRepository contract. It knows nothing of the actual implementation of the repository, it is resolved at run time using IoC, so this core dll has no reference to the NHibernate dll's.
  • MyProject.Data.NHibernate.dll: the implementation of the repository is contained within this assembly that has all the necessary references to the NHibernate dll's.

My Repository implementation looks something like this:

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    ...
    public virtual IQueryable<T> All()
    {
        IList<T> entities = Session
            .CreateCriteria( typeof( T ) )
            .List<T>();
        return entities.AsQueryable<T>();
    }
    ...
}

So in my core dll I can get a reference to my repository and do something like:

IList<Person> people = myRepository.All().ToList();

That seems to work well, it queries the database and returns all the rows from the Person table.

However, now what I want to do is add predicates:

IList<Person> daves = myRepository.All().Where(p => p.Name == "Dave").ToList();

This works fine, but of course what happens is that NHibernate first queries the database to return ALL rows, and then LINQ filters the results to only return the ones whose name is "Dave".

I've been looking all over the internet, but I haven't found how to implement this, also I found many things that seem to be outdated, for example, I often saw calls to the NH session.Linq() method, I looked all over my dll's, this method is nowhere to be found...

If anyone could point me to the right direction, maybe with a little example or something, I would be very greatful.

Thankd you very much!

Was it helpful?

Solution

It is quite simple:

Use session.Query<T>():

public virtual IQueryable<T> All()
{
    return Session.Query<T>();
}

Query<T> is an extension method that lives in the namespace NHibernate.Linq.

session.Linq is no longer supported. It was the LINQ provider for NHibernate prior to version 3 and has been replaced by Query<T>.

OTHER TIPS

You might want to look at using the specification pattern with your repository. There is an example of an implementation with NHibernate here from the NHibernate 3.0 Cookbook, which is an excellent resource worth getting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top