knittl
knittl

Reputation: 265251

Force equality operator when comparing to null in NHibernate

NHibernate is clever when it comes to comparing fields to null. Consider the following LINQ statement:

string s = null;
var rows = session.Query<Entity>
  .Where(e => e.SomeField == s)
  .ToList();

The statement is transformed into the SQL query

SELECT ...
FROM entity_table
WHERE some_field IS NULL;

In some cases I don't want this behavior. I want the resulting query to contain the some_field = NULL restriction (which is never true).

(How) can I instruct NHibernate to do this? Or do I have to write two queries and handle the null-case explicitly in code?

Note that this is in the context of NHibernate, not linq-to-sql. NHibernate cannot transform object.Equals(e.SomeField, s) into an SQL query. Also, comparing to a variable which is currently null and comparing to the null keyword directly will yield the same query with NHibernate.

Upvotes: 0

Views: 510

Answers (1)

Najera
Najera

Reputation: 2879

You can use QueryOver, but will generate parameterized query:

string s = null;

var rows = session.QueryOver<Entity>()
    .Where(Expression.Eq(Projections.Property<Entity>(x => x.SomeField), s))
    .List();

Upvotes: 1

Related Questions