Reputation: 119
I have the following problem: I have a nullable column in my database table. I want to be able to add a filter for it in my Where clause. However, when the column is in fact null, I get an error: 'Object reference not set to an instance of an object.'
public class MyClass
{
public virtual float? Id { get; set; }
}
// When querying:
...
MyClass myClass = null;
var query = GetCurrentSession().QueryOver<MyClass>(() => myClass);
// The following all give the same null reference error.
(1) query.Where(() => myClass.Id.ToString() == "...");
(2) query.Where(() => myClass.Id.Value.ToString() == "...");
(3) query.Where(() => myClass.Id != null && myClass.Id.ToString() == "...");
(4) query.Where(() => myClass.Id != null && myClass.Id.Value.ToString() == "...");
(5) query.Where(() => myClass.Id.HasValue && myClass.Id.ToString() == "...");
(6) query.Where(() => myClass.Id.HasValue && myClass.Id.Value.ToString() == "...");
A somewhat similar problem can be found here, but didn't help me out.
It looks like lazy evaluation within the Where clause doesn't seem to take place. I get the feeling, I'm overlooking something very obvious here, however can't seem to find it.
UPDATE: Okay, so based on Novakov suggestion below, I was able to fix the nullable float comparison issue. However, the same problem still remains for (other) string values. For example, I want to be able to do something like this, and the same exception keeps popping up, even if I check for null in the query.
query.WhereRestrictionOn(() => myClass.MyJoinedTable.MyField.ToLowerInvariant()).IsLike("%test%");
Upvotes: 1
Views: 1705
Reputation: 123861
With a QueryOver
syntax (see 16. QueryOver Queries) should look like this:
I. nullable property
query.Where(() => myClass.Id == searchedValue)
Does not matter, that the property is nullable. The above statement will take only these rows, which do have value in DB and which value is equal to searchedValue
II. searching for string
MyJoinedTable myJoinedTable = null;
query
...
.JoinQueryOver<MyJoinedTable>(() => myClass.MyJoinedTable, () => myJoinedTable)
.WhereRestrictionOn(() => myJoined.Field)
.IsInsensitiveLike("test", MatchMode.Anywhere);
Above we can see that we firstly join the MyJoinedTable using JoinQueryOver
and then we use SQL LOWER()
with built in NHiberante method IsInsensitiveLike(")
Upvotes: 1