QueryOver and IN clause

1,769 views
Skip to first unread message

tillias

unread,
Oct 16, 2011, 4:51:15 AM10/16/11
to nhusers
Hello!

I'm using following code to emulate IN clause in NHibernate 3.2 and
query over:

var query = session.QueryOver<SettingsEntity>().Where(s =>
intSettingsIDs.Contains(s.ID));
return query.List();

In the code above I've got intSettingsIDs -- array of integers. When I
run query exception is thrown:


16/10/2011 12:47:48.47Error Error while loading settings -
System.Exception: Unrecognised method call:
System.Linq.Enumerable:Boolean Contains[TSource]
(System.Collections.Generic.IEnumerable`1[TSource], TSource)
at
NHibernate.Impl.ExpressionProcessor.ProcessCustomMethodCall(MethodCallExpression
methodCallExpression)
at
NHibernate.Impl.ExpressionProcessor.ProcessBooleanExpression(Expression
expression)
at NHibernate.Criterion.QueryOver`2.Add(Expression`1 expression)
at
NHibernate.Criterion.QueryOver`2.NHibernate.IQueryOver<TRoot,TSubType>.Where(Expression`1
expression)

On the other hand folowing code works perfectly:

var query = session.CreateCriteria<SettingsEntity>().Add(
Restrictions.In("ID", intSettingsIDs));
return query.List<SettingsEntity>();

What am I doing wrong with the first approach?

Thanks!

Ted Parnefors

unread,
Oct 16, 2011, 5:51:18 AM10/16/11
to nhu...@googlegroups.com
Why not try a query like this instead:

session.QueryOver<SettingsEntity>().WhereRestrictionOn(s => s.Id).IsIn(inSettingsIDs).List<SettingsEntity>();

> --
> You received this message because you are subscribed to the Google Groups "nhusers" group.
> To post to this group, send email to nhu...@googlegroups.com.
> To unsubscribe from this group, send email to nhusers+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/nhusers?hl=en.
>

Ilia Ternovich

unread,
Oct 16, 2011, 10:33:55 AM10/16/11
to nhu...@googlegroups.com
Thank you very much Ted!

It works like a charm.

PS. Linq-Lambda contains version (first one from my original question)
is more intuitive for those who migrate from EF

2011/10/16 Ted Parnefors <ted.pa...@gmail.com>:

Richard Brown (gmail)

unread,
Oct 16, 2011, 12:06:52 PM10/16/11
to nhu...@googlegroups.com
Hi,

There is also an extension method that allows you to write the query like
this:

return
session.QueryOver<SettingsEntity>()
.Where(s => s.ID.IsIn(intSettings))
.List();

You'll need to add a using NHibernate.Criterion statement. Also note, you
don't need the final cast on the List() call (if you're returning the same
type as the root entity).

It's also worth noting that QueryOver is not the NHibernate LINQ provider -
it's a strongly/statically typed syntax that wraps the ICriteria API. There
is also a LINQ provider which might give you the kind of syntax you're
looking for:

return
session.Query<SettingsEntity>()
.Where(s => intSettings.Contains(s.ID))
...

Hope that helps.

Richard

Reply all
Reply to author
Forward
0 new messages