Reputation: 9411
Having a really hard time trying to figure out a "where in" equivalent in nHibernate.
I am using nHibernate 3. What's the best way to do something like this:
SELECT DISTINCT
U.ID as CID
FROM User U
WHERE
CID IN (
SELECT RID
FROM ResellerSites rs
INNER JOIN Locations l ON l.ID = rs.LID
WHERE l.ID = 14
)
I found an examples somewhere that says I need to have something like this:
var criteria = session.CreateCriteria(typeof(User));
var resellerSites = new[] { new ResellerSite { Id = 1 }, new ResellerSite { Id = 2 } };
criteria.Add(new InExpression("ResellerSite", resellerSites));
This is what I have so far:
var resellerSites = session.CreateCriteria<ResellerSite>("p")
.CreateCriteria("p.Locations", JoinType.InnerJoin)
.Add(Restrictions.Eq("locationID", locationId))
.List<ResellerSite>();
criteria.Add(new InExpression("ResellerSite", resellerSites));
var finalList = criteria.List<ResellerSite>();
The "criteria.Add(new InExpression" part is giving me an intellisense error, as InExpression seems to expect something like:
new[] { new ResellerSite { Id = 1 }, new ResellerSite { Id = 2 } };
Like in the first example.
Should I do a for loop like:
foreach (var site in resellerSites)
{
//somehow push into a new[] ?
}
or something like that or is there a better way?
Perhaps this entire approach is wrong?
Upvotes: 0
Views: 648
Reputation: 15433
I'd say that the typing problem comes from the double CreateCriteria and the single ToList()
Difficult to say without the table definitions, but, rereading you code, I wonder why you need the inner join with the locations. May be you can rewrite your query as :
SELECT DISTINCT
U.ID as CID
FROM User U
INNER JOIN ResellerSites rs
on U.ID = rs.RID
and rs.LID=14
And have your code like (not tested and not optimal as you could have only one criteria query with join)
var resellerSites = session.CreateCriteria<ResellerSite>()
.Add(Expression.Eq("locationID", locationId))
.List<ResellerSite>();
criteria.Add(new InExpression("ResellerSite", resellerSites.ToArray()));
var finalList = criteria.List<ResellerSite>();
Upvotes: 1
Reputation: 12261
You can easily convert resellerSites
to array using Linq:
criteria.Add(new InExpression("ResellerSite", resellerSites.ToArray()));
Also this question may help: Cannot use collections with InExpression
Upvotes: 1