简体   繁体   中英

Fluent NHibernate QueryOver: avoid orderby null reference table

I'm using Fluent NHibernate to map a fairly simple database. I'm having a problem with the following situation. Let's say my class looks like so

ClassA
-------
...
string A_Name;
ClassB InnerObject;    <- can be 'null' in the code, 
                          because not every A record has a matching B record


ClassB
-------
...
string B_Name;

I'm working with JQuery datatables, where I display per record/row the A_Name and InnerObject.B_Name . This all works for simply accessing the data. I can manually test if the InnerObject is null and if so, just show an empty string value. This works and is good.

The problem I'm having is how to use the correct syntax for ordering on that column. Depending on which column the users want to sort, I have something like this:

    if (sort on innerObject's B_Name)
    {
        query.OrderBy(() => innerObjectAlias.B_Name).Asc();
    }

I'm fairly certain I have my mapping correctly set up and that the problem here is that I need to be able to 'skip' the sorting (or modify) if the innerObject is null .

So something like this would be nice, but obviously doesn't work (because I think Fluent NHibernate never actually assigns a value to the alias right?):

    if (sort on innerObject's B_Name AND innerObjectAlias != null)
    {
        query.OrderBy(() => innerObjectAlias.B_Name).Asc();
    }

Any help would be greatly appreciated.

This nullability check is possible. But it would not be at a place of adding orders ( ORDER BY ). It must be fixed in the moment when we create association ( JOIN ). Instead of this:

// instead of this
// resulting in INNER JOIN
query.JoinAlias(root => root.InnerObject, () => innerObjectAlias);

// we must use this
query.JoinAlias(root => root.InnerObject, () => innerObjectAlias
              , JoinType.LeftOuterJoin);

// which will result in LEFT OUTER JOIN

Then, even this statement will return correct rows, partially sorted by existing columns

query
   .OrderBy(() => innerObjectAlias.B_Name)
      .Asc
   ...

NOTE: if want to drive placement of NULL rows we can order by some projection, doing magic like mentioned here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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