views:

444

answers:

1

I am try to convert the following NHibernate query using dyanmic instantiation into an IList<t> rather than an IList.

IList<AllName> allNames =
  (IList<AllName>)Session.CreateQuery(
  @"select new AllName(
  name.NameId, name.FirstName, origin.OriginId, origin.Description,
  name.Sex, name.Description, name.SoundEx
  ) from Name name join name.Origin origin")
  .SetFirstResult(skip)
  .SetMaxResults(pageSize);

Running this I get the following error:-

Unable to cast object of type 'NHibernate.Impl.QueryImpl' to type 'System.Collections.Generic.IList`1[Domain.Model.Entities.AllName]'.

I know that I can return

IList results = Sesssion.CreateQuery(...

but my service layers expect an

IList<AllName>

How can I achieve this?

+4  A: 

One option would be to write an IList<T> implementation which proxies to an IList, casting where appropriate. It shouldn't be too hard to do, albeit somewhat tedious. LINQ will make this slightly easier in terms of implementing IEnumerable<T> etc - you can just call the underlying iterator and call Cast<T>() on it, for example.

Another solution would be to create a new List<T> from the returned list:

IList query = Session.CreateQuery(...);
IList<AllName> allNames = new List<AllName>(query.Cast<AllName>());

EDIT: As Sander so rightly points out, this is what ToList is for:

IList query = Session.CreateQuery(...);
return query.Cast<AllName>().ToList();

EDIT: All of this has been NHibernate-agnostic, as it were - I don't actually know much about NHibernate. Rippo has now found a much simpler answer - call List<AllName> instead (which is an NHibernate method).

Jon Skeet
When you're using the `.Cast<T>()` extension method, you can just as well add an `.ToList()`.
Sander Rijken
Thanks Jon, the cast worked. Is there any kind of performance hit here? My page size is set to 50 records so I am not returning an enormous amount of data.
Rippo
@sander: doh! Why didn't. I think of that? :)
Jon Skeet
Jon, found another way, just posting in case anyone else looks at this post. I can simply do **return query.List<AllName>();**
Rippo
@Rippo: That's where my lack of knowledge of NHibernate has let me down :) I'll edit it into the answer just to make it more visible.
Jon Skeet