Variant
Variant

Reputation: 17365

Linq for NHibernate, ordering by a property of a nullable association

Kindly consider this simplified scenario:

Two NHibernate Entities:

public class Foo {
  public virtual Bar Bar {get; set;}
}

public class Bar {
  public virtual string Name {get; set;}
}

I need to sort a collection of Foo by their's Bar's name. however, not all Foos have Bars assigned. For some entities it is null

The obvious:

Foos.OrderBy(f => f.Bar.Name)

Throws an Exception.

The only way I can think of to handle it is to add a formula to Foo that I can use in the OrderBy clause. I have a feeling that there got to be a better and more elegant solution.

Any ideas?

Update

This issue is fixed in NHibernate 3.1 - https://nhibernate.jira.com/browse/NH-2412

The outer join for the OrderBy is "Built In"

Upvotes: 2

Views: 448

Answers (2)

Vadim
Vadim

Reputation: 17957

You need to specify a join to Bar

If you're using NHibernate >=3.0.

from foo in session.Query<Foo>()
join bar in session.Query<Bar>() on foo.Bar.Id equals bar.Id into leftJoinFooBar
from bars in leftJoinFooBar.DefaultIfEmpty()
orderby bars.Name
select foo

if you/re using NHibernate <3.0. You'll have to use Criteria or HQL.

Upvotes: 2

Arunas
Arunas

Reputation: 918

Check if Bar is null and pick a default string value if it is otherwise use Bar.name:

Foos.OrderBy(f => (f.Bar != null)?f.Bar.Name:"")

Upvotes: 0

Related Questions