简体   繁体   English

NHibernate.Linq-Where子句中的Nullable类型时查询错误

[英]NHibernate.Linq - Error querying when Nullable types in Where clause

I have the following NHibernate Linq query: 我有以下NHibernate Linq查询:

From eachLine In myNhSession.Query(Of SamplePoco)()
     Where eachLine.SampleIntField = 1234

The property SamplePoco.SampleIntField is type Nullable(Of Int32) 属性SamplePoco.SampleIntField的类型为Nullable(Of Int32)

When I run the query, I get the following exception: 运行查询时,出现以下异常:

System.InvalidCastException: Unable to cast object of type 'NHibernate.Hql.Ast.HqlCoalesce' to type 'NHibernate.Hql.Ast.HqlBooleanExpression'

If I change the property type to Int32 , it works. 如果我将属性类型更改为Int32 ,它将起作用。 It seems that Nullable types are automatically converted into a coalesce expression by the Linq compiler. 看来Linq编译器会自动将Nullable类型转换为合并表达式。

Debugging the NHibernate, I just found out that this Where clause was converted into: {where ((eachLine.SampleIntField == 1234) ?? False)} . 在调试NHibernate时,我刚发现将Where子句转换为: {where ((eachLine.SampleIntField == 1234) ?? False)} As I can understand, the whole condition comparison was translated to be coalesced instead of just the Nullable property. 据我了解,整个条件比较被转换为合并的,而不仅仅是Nullable属性。

If I put this way eachLine.SampleIntField.Equals(1234) it doesn't work as well ('Equals not implemented' exception) 如果我用这种方式设置eachLine.SampleIntField.Equals(1234)它就不能正常工作(“未实现等于”例外)

If I change the query to the following code, it works: 如果将查询更改为以下代码,则它可以工作:

From eachLine In myNhSession(Of SamplePoco)()
     Where {1234}.Contains(eachLine.SampleIntField)

(not elegant) (不优雅)

Another code that works as well (coalescing the field properly as I was expecting by the first query): 另一个也能正常工作的代码(如我在第一个查询中所期望的那样,正确地对字段进行了提示):

From eachLine In myNhSession(Of SamplePoco)()
 Where If(eachLine.SampleIntField,0) = 1234

Any suggestions to keep it simple? 有什么建议可以保持简单吗?

I think the most explicitly clear way to put it, that NHibernate handles, is: 我认为NHibernate处理最明确的方法是:

From eachLine In myNhSession.Query(Of SamplePoco)()
     Where eachLine.SampleIntField.HasValue AndAlso eachLine.SampleIntField.Value = 1234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM