Cast an IList to an IList<t> using dynamic instantiation
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);
开发者_StackOverflow中文版
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?
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).
精彩评论