views:

797

answers:

2

I use LINQ a lot in general, especially LINQ-to-Objects, hence I'm rather fluent in LINQ.

I was considering to use LINQ-to-NHibernate as the query language for my NHibernate project. When I wrote some tests, I noticed that LINQ-to-NHibernate doesn't make the same query as ICriteria. Since I'd prefer to use LINQ, I'd like to ask if anyone knows of similar differences, or should I just not bother about performance in general (The high-performance operations would need some tweaking with NHibernate anyway as far as I get it). See the following example:

var query = (from inputItem in session.Linq<InputItem>()
             where inputItem.Project == project select inputItem).First();

gives me the following SQL:

SELECT this_.ID as ID0_1_, this_.Name as Name0_1_, this_.Project_id as Project3_0_1_, project1_.ID as ID1_0_, project1_.Name as Name1_0_
    FROM "InputItem" this_ left outer join "Project" project1_ on this_.Project_id=project1_.ID
    WHERE this_.Project_id = @p0 limit 1;@p0 = 1, @p1 = 1

whereas

var criteria = session.CreateCriteria<InputItem>();
criteria.Add(Expression.Eq("Project", project));
criteria.SetMaxResults(1);
criteria.List();

gives

SELECT this_.ID as ID0_0_, this_.Name as Name0_0_, this_.Project_id as Project3_0_0_
    FROM "InputItem" this_
    WHERE this_.Project_id = @p0 limit 1;@p0 = 1, @p1 = 1

Clearly, the LEFT JOIN wouldn't be necessary.

Is something wrong with my LINQ query or is it just a limitation? And should I worry about it in the first place?

Icey

EDIT: I tried changing the LINQ statement to the following:

var query = (from inputItem in session.Linq<InputItem>()
             where inputItem.Project.ID == project.ID
             select inputItem).First();

the generated SQL is the same, though.

A: 

Do you use the latest release?

I'm yet to try it myself. But I have to say, I always bump into issues while trying to use Linq-to-NHibernate. Well, maybe I'm too much newbie to both of them... but Linq is supposed to be intuitive, and there's nothing intuitive in getting null reference from a damn simple query (like your one) that works perfectly in HQL.

But it's understandable since that was in development. And still is, I suppose ;-)

queen3
Yes, I use version 1.0 of Linq-to-NHibernate. Btw, I don't get null references. The only Place, where you might get a null reference exception here would be First() in the end. Try using FirstOrDefault(). And I'd like to skip HQL as I sincerely hate magic strings wherever they are anyhow avoidable.
Icey
+1  A: 

It looks to me as if NHibernate.Linq doesn't support this optimisation right now. I think you'll need to use a criteria query, or HQL, or wait until the fully integrate LINQ provider is released (slated for NHib v3 I think).

Cheers, John

John Rayner
So I take it, I didn't make any obvious mistake.
Icey