Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do create a generic Session.QueryOver<T>?

Tags:

c#

nhibernate

Out of curiosity is it possible to do something like this using NHibernate 3?

public IQueryable<T> FindAll<T>()
{
   return Session.QueryOver<T>().List().AsQueryable();
}

I get a compilation error saying something like...

The Type T must be a reference type in order to use it as a parameter T.

I was wondering if I could create an extension method to Session.QueryOver to handle a generic type.

I could replace this using something like

return Session.CreateCriteria(typeof (T)).List<T>().AsQueryable();

But was keen to use the features of the query api. Any ideas? maybe missing something obvious!!

like image 731
Aim Kai Avatar asked Sep 25 '10 22:09

Aim Kai


1 Answers

You are missing a restriction on T:

public IQueryable<T> FindAll<T>() where T : class
{
   return Session.QueryOver<T>().List().AsQueryable();
}

where T : class defines that T has to be a reference type. (As the compile error demanded, apperently QueryOver<T> is restricted to reference type). If a type parameter has constraints applied to it, any generic method using this method with a generic parameter of its own has to apply similar constraints.

For a complete overview of generic type parameter constraints, see msdn.

like image 125
Femaref Avatar answered Nov 08 '22 09:11

Femaref