Linq to NHibernate vs. ICriteria

匿名 (未验证) 提交于 2019-12-03 02:50:02

问题:

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.

回答1:

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



回答2:

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 ;-)



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!