views:

499

answers:

1

Is there any way to get at the types of objects I would expect NHibernate to place in an ICriteria object as the result of running a query? In this code sample, I can get at the types of my objects if they aren't null, but what if they are? Also, depending on the data returned, one "row" (object[]) may have null fields in places where other rows don't - forcing me to enumerate through all rows (worst case) to determine what each column (index of object[]) should be.

Where can I find the expected type for the object (the expected type for each of the objects in the array I've created - obviously it wouldn't be on my array, but I would expect it to be somewhere in the ICriteria hierarchy)?

DetachedCriteria dc = DetachedCriteria.For<MyObject>().Add(...).SetProjection(...);

IList<object[]> list = dc.GetExecutableCriteria(session).List().OfType<object[]>().ToList();

foreach(object [] o in list)
{
   foreach(object p in o)
   {
      if(p != null)
         Type t = p.GetType();
      else
         throw new ApplicationException("Query returned null for column");
   }
}

I ask this because having to actually examine the results returned by NHibernate seems like the wrong way to go about this. Reflection doesn't appear to be any help either, because I can't find an instance to my object's types anywhere but on the actual result "row" / "column" when examining the ICriteria object (a CriteriaImpl object) returned.

I ask because I'm trying to dynamically create a DataTable from an NHibernate result, and I want to have the columns strongly typed.

A: 

The types returned are the types you queried for. If your users are adding custom columns and querying freely, you won't know what you're querying for, so you can't get a strongly-typed result without inspecting the actual objects.

AFAIK this is a limitation in NHibernate.

Mauricio Scheffer
I may be missing something, but when I use ADO.NET to run a SQL query ("SELECT Name FROM MyTable" on an example database where Name is of Type 'string'), I can get a dynamic DataTable with 1 column called 'Name' with of Type string. This column is strongly typed (DataType == typeof(string)), even if every 'Name' value returned from my query is null. No actual inspection is required.With Hibernate, it would appear that I have to examine every result looking for the first one != null so I can get a Type from it (because NHibernate returns object Types and you can't call null.GetType()).
Mick
You're right, I forgot about the DataType property. It is a limitation in NHibernate then.
Mauricio Scheffer