I have 3 NHibernate entities
Division
{
Id (PK),
Name
}
District
{
Id (PK),
Name
}
Doctor
{
Id (PK),
Name,
Division,
District
}
I want to get doctors filtering by the division and district.
I can write query by two way, say I have a user-selected Division and I want the doctors under this division.
First way:
var doctors = doctorRepository
.FilterBy(x => x.Division.Id == selectedDivision.Id)
.ToList();
Second Way:
var doctors = doctorRepository
.FilterBy(x => x.Division == selectedDivision)
.ToList();
My First question is, which is the best way considering the performance?
I checked the sql profiler for both queries.
For first query, the generated sql contains a left outer join with division table. I can’t understand why it needs to join with Division table as the DivisionId reside in the Doctor table. Will this extra join reduce the performance?
My Second question: if I want to query from the doctor repository using Division and District and both division and district can be null sometimes, in this case how should I write this query in NHibernate Linq?
It may not strictly need to, probably it’s just that this detail isn’t optimized by the NHibernate Linq provider. Unless your database engine realizes that it can be optimized away (look at the execution plan for the SQL), it will affect performance. How much is impossible to tell in the general case.
Consider a query such as:
When executed by Linq2NH it will be converted to SQL. If x.Division is NULL nothing bad will happen, because the expression will never be dereferenced in .NET. I’m uncertain if NHibernate will try to dereference selectedDivision (causing NRE) or if it’s smart enough to convert
selectedDivision.Idinto NULL ifselectedDivisionis NULL. Try it! Otherwise, a safer way is to write:NHibernate is smart enough to generate IS NULL in the SQL if divId happens to be null.
Null as indication to avoid filter
I typically use a pattern such as: