views:

171

answers:

1

Hello,

I'm using NHibernate as a persistency layer and I have many places in my code where I need to retrieve all the columns of a specific table (to show in a grid for example) but i also need a fast way to get specific item from this collection.

The ICriteria API let me get the query result either as a unique value of T or a IList of T. I wonder if there is a way to make NHibernate give me those objects as an IDictionary where the key in the object's Id and the value is the object itself. doing it myself will make me iterate all over the original list which is not very scalable.

Thank you.

+1  A: 

If you are working with .NET 3.5, You could use the Enumerable() method from IQuery, then use the IEnumerable<T>.ToDictionary() extension method :

    var dictionary = query.Enumerable().ToDictionary(r => r.Id);

This way, the list would not be iterated twice over.

You mention using ICriteria, but it does not provide a way to lazily enumerate over items, whereas IQuery does.

However, if the number of items return by your query is too big, you might want to consider querying the database with the key you'd have used against the IDictionary instance.

Jerome Laban
Thanks Jerome, Do you know why the ICriteria interface does not provide the Enumerable() method as well? why should I use IQuery over ICriteria?
Moshe Levi