Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate Linq In Clause

Tags:

Is it possible to get Nhibernate linq to generate a query with an "In" clause? e.g. - Where AnID in (x,y,z)?

like image 932
CocoB Avatar asked Mar 30 '10 16:03

CocoB


People also ask

How do I use LINQ with NHibernate?

NHibernate 3.0 introduces the Linq to NHibernate provider, which allows the use of the Linq API for querying with NHibernate. IQueryable queries are obtained with the Query methods used on the ISession or IStatelessSession. (Prior to NHibernate 5.0, these methods were extensions defined in the NHibernate.Linq namespace.)

What's new in Chapter 18 of NHibernate?

Chapter 18. Linq Queries Chapter 18. Linq Queries Chapter 18. Linq Queries NHibernate 3.0 introduces the Linq to NHibernate provider, which allows the use of the Linq API for querying with NHibernate. IQueryable queries are obtained with the Query methods used on the ISession or IStatelessSession.

How are IQueryable queries obtained in NHibernate?

IQueryable queries are obtained with the Query methods used on the ISession or IStatelessSession. (Prior to NHibernate 5.0, these methods were extensions defined in the NHibernate.Linq namespace.) A number of NHibernate Linq extensions giving access to NHibernate specific features are defined in the NHibernate.Linq namespace.

How to use NHibernate with Isin extension?

However the ultimate solution is to just add NHibernate.Criterion namespace and use IsIn extension method. This operation simplify our query into single lambda expression NHibernate – generating WHERE IN … OR … queries


2 Answers

I don't know the state of nHibernate with respect to generating all the potential LINQ queries, but you should be able to use .Contains() to generate an IN.

var list = new int[] { x, y, x }; var q = db.Entities.Where( e => list.Contains( e.AnID ) ); 
like image 94
tvanfosson Avatar answered Sep 21 '22 12:09

tvanfosson


Agreed, this does work. I found the generated SQL for 'not in' to be strange though (as of 3.3.0 GA)

... from   mytable t0_ where   case     when t0_.testValue in (               @p0 , @p1 , @p2           ) then 1           else 0     end=@p3 @p0 = 9 [Type: Int32 (0)], @p1 = 99 [Type: Int32 (0)], @p2 = 109 [Type: Int32 (0)], @p3 = False [Type: Boolean (0)], ... 

Seems a bit odd to 'case' this when 'not in' would have been clearer (not that I plan on reading every line, but in a trace/profile maybe).

(... later that day ...)

I realized that the above 'strange' choice of SQL was only when I used

.Where(e => list.Contains(e.AnID) == false) 

If I used

.Where(e => !list.Contains(e.AnID)) 

The SQL generated is much cleaner (using 'not in')

like image 22
MarkClouden Avatar answered Sep 19 '22 12:09

MarkClouden