A colleague asked me for help with a complex NHibernate query. He had written a query using the NHibernate Linq support but when he tried to execute the query, NHibernate complained with the following error message:
‘'Unrecognised method call: System.Int64:Boolean Contains(Int64)”
Let’s have a look at his query first:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_session.Query<Product>() | |
.Where(p => shoppingBasket.Products.Contains(p.ProductId)) | |
.Select(p=> p); |
It seems that NHibernate cannot translate the Contains() call in a related NHibernate query. To fix this, we switched from the Linq syntax to the QueryOver syntax:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var productIds=shoppingBasket | |
.Products | |
.Select(p=> p.ProductId) | |
.ToArray(); | |
_session.QueryOver<Product>() | |
.WhereRestrictionOn(p => p.ProductId) | |
.IsIn(productIds) | |
.Select(p => p); | |