SQL IN statement in Linq for NHibernate
I have this Lookup to group ResultId by Symbol. I have Linq query below but I cannot make SQL IN statement by using Contain() which is state by this post http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql
// This will group ResultIds (Guid) by their symbol (string).
var asd = ResultIdsAndSymbols.ToLookup(x => x.Symbol, y => y.ResultID);
foreach (var qwe in asd)
{
var Numbers = (from t in S开发者_如何学JAVAession.Query<TableName>()
where qwe.Contains(t.ResultID)
select t.Number).ToList();
}
Update:
After retrying this code and deep analyzing the error (System.InvalidCastException: Object must implement IConvertible), I got this informative error message: "Failed to convert parameter value from a Grouping to a Guid". qwe
is a type of IGrouping<string, Guid>
and it will become IEnumerable<Guid>
which should not be a problem like we pass this into a List
constructor or used in foreach
statement. The exception thrown in System.Data.SqlClient
. I think NHibernate simply pass the Grouping<TKey, TElement>
into the sql parameter that cause the error. NHibernate should be designed to enumerate to any IEnumerable<T>
and generate the SQL IN query just like how it does for List<T>
.
The List<T>
, Array[], Stack
work well. So I change the code to this:
where qwe.ToList().Contains(t.ResultID)
Update: Issue reported: https://nhibernate.jira.com/browse/NH-2762
The NHibernate LINQ provider is limited when it comes to the IN clause. It seems to only work with collections where T is a simple type, e.g. List<string>
or List<int>
.
This works in NHibernate 3.1 (not tested in earlier versions):
var asd = ResultIdsAndSymbols.ToLookup(x => x.Symbol, y => y.ResultID);
foreach (var qwe in asd)
{
List<int> list = qwe.ToList();
var Numbers = (from t in Session.Query<TableName>()
where list.Contains(t.ResultID)
select t.Number).ToList();
}
精彩评论