views:

151

answers:

1

This is the first time I've used NHibernate for a big project so bear with me. Basically, I need to run a search based on 5 fields.

I want to display the results in a table. Here is a test I've written that basically gets all Clients that have Intakes with a Staff named "DII". When I run it, I get an error saying that some of the Intakes are null.

var name = new Name("Alice", "B." "Cooper");
var staff = "DII";
var fileNumber = 12345;

var crit = NHibernateHelper.GetCurrentSession().CreateCriteria(typeof(Client));
var result = crit.CreateAlias("Intakes", "i");            
        .Add(Restrictions.Like("Name.First", name.First + "%"));
        .Add(Restrictions.Like("Name.Middle", name.Middle + "%"));
        .Add(Restrictions.Like("Name.Last", name.Last + "%"));   
        .Add(Restrictions.Eq("i.Staff", staff));            
        .Add(Restrictions.Eq("i.FileNumber", fileNumber));
        .List<Client>();

foreach (var client in result)
{
    Assert.IsTrue(client.Intakes.All(i => i.Staff == "DII");
}

However, it does return the correct number of Clients. My question is, how do I only iterate through the associated Intakes that would've been returned by the query generated by the above ICriteria?

I tried modifying the last line to be:

Assert.IsTrue(c.Intakes.Where(i => i != null).All(i => i.Staff == "DII"));

And it works correctly, except that the SQL generated is:

SELECT (Client + Intake Join) ...
SELECT FROM IntakeTable ...
SELECT FROM IntakeTable ...
SELECT FROM IntakeTable ...
(for each Intake that was returned with the join)

Meaning the it runs the Join, and then fetches all the Intakes again, which is not what I want.

A: 

Doh, figured it out. It was because of my mapping. I was using:

<list ... />

...and ordering by a non-position column. Because of that I was getting a bunch of null entries in my Intakes association.

I turned it into an ordered bag and everything worked as you'd expect.

cdmckay