8

我有两个类似的查询理论上返回相同的结果:

var requestNotWorking = SessionManagement.Db.Linq<Item>(false).Where(i => 
                        i.Group != null && i.Group.Id == methodParameter)
                       .ToList();

此请求返回 0 个项目,即使它应该返回一个。以下是后者的重写,但调用了该ToList()方法。此请求有效并返回第一个查询中预期的项目!

var requestWorking = SessionManagement.Db.Linq<Item>(false).ToList().Where(i => 
                     i.Group != null && i.Group.Id == methodParameter).ToList();

注意:SessionManagement.Db.Linq<Item>(false)是一个通用的 Linq to Nhibernate 方法,其布尔属性确定请求是必须在缓存中执行(true)还是在数据库中执行(false)。据说这种方法没有任何问题,因为它在解决方案的许多其他部分都可以正常工作。Item 的映射没什么花哨的:没有包和以下参数: lazy="false" schema="dbo" mutable="false" polymorphism="explicit"

为什么会这样?

编辑

requestNoWorking 生成的 sql 请求以:

(Item.Group_ID is not null) and Item.Group_ID=@p0',N'@p0 int',@p0=11768

requestWorking生成的sql请求大致是一个select * from dbo.Items

4

3 回答 3

4

i'm assuming the nhibernate session thing you've got going on there returns a queryable. if so, the evaluation of the first query is delayed until the .ToList() call, and the entire query is run on the server. I would suggest that you run a trace on the sql server if possible, or perhaps download NHProf to see what the actual query being executed is.

the second query is evaluated as soon as you hit the first .ToList(), so you're pulling the whole table back from the db, and then filtering using .net. i honestly can't tell you why they would be evaluating differently, but i assume there is something with the mapping/configuration that is causing the db query to be written slightly wrong.

于 2013-01-03T16:00:08.890 回答
1

我对您关于c.Group.Id != null. 但是,删除它并没有改变任何东西。我发现删除mutable="false"属性解决了这个问题。这似乎有点神奇,但它奏效了。

我发布的请求实际上是在检查更新/删除可能性的方法中发生的。我的结论是,以某种方式使 Item 不可变会导致结果失败。但我不明白为什么 requestWorking 工作了!

于 2013-01-03T17:10:19.277 回答
0

All I can see is that in the 2nd version, your Where is executed by LINQ to Objects rather than LINQ to NHibernate. So the first version must do something that LINQ to NHibernate doesn't digest very well.

I'm thinking it's the i.Group != null that LINQ To NHibernate has a problem with, seeing that the use of null is CLR-specific. You may need to use another construct in LINQ to NHibernate to test for empty field values.

于 2013-01-03T15:59:58.790 回答