I'm working with an object model in Castle ActiveRecord that represents pregnant women. It's a simple tree structure:
Patient
Visit
Delivery
A Patient has 0 or more Visits and a Visit has 0 or more Deliveries. I've mapped everything to the database, and I can loop through the Patient>Visit>Delivery hierarchy and print out everything. I can also use LINQ Where clauses like this:
var recent = new DateTime(1980, 1, 1);
var patients = ActiveRecordLinq
.AsQueryable<Patient>()
.Where(p => p.DateOfBirth > recent)
.OrderBy(p => p.LastName)
.ThenBy(p => p.FirstName)
.ThenBy(p => p.DateOfBirth);
This correctly gives me a list of patients born since 1/1/1980.
Now suppose I want to only look at all the visits for those patients, to analyze them or whatever. I'd think the correct way is something like this:
var visits = patients.SelectMany(p => p.Visits);
Based on how LINQ works, this should give me a flattened list of all the visits of all the patients from the original query. The visits
variable does in fact come out as an IQueryable<Visit>
. But when I try to enumerate the results, I get this:
Unable to cast object of type 'Patient' to type 'Visit'.
Similarly, I can get the birthdates of several patients like this:
var patients = ActiveRecordLinq.AsQueryable<Patient>().Take(10);
var birthDates = patients.Select(x => x.DateOfBirth);
foreach (var date in birthDates.ToList().OrderBy(x => x))
{
Debug.Print(date.ToShortDateString());
}
But if I take out that ToList in the foreach, I get a NullReferenceException.
Clearly there are some things about the Castle ActiveRecord implementation of LINQ (or its NHibernate base) that I'm failing to grasp. Can anyone offer me some help?