HQL query results "cannot be used in this generic collection" when returning a subclass
Given the following:
A Company has a collection of Product objects.
An Area has a collection of Product objects. Any given Product has a Company and an Area. SpecialProduct is a subclass of Product.I'm using the following HQL query in NHibernate.
// return all SpecialProperty objects for a given company and area.
IQuery query = session.CreateQuery("select product from Company as company " +
"join company.Products as product " +
"join product.Area as area " +
"where company.Id = :coId " +
"and area.Id = :arId " +
"and product.class = MyNamespace.DomainModel.SpecialProduct ")
.SetInt64("coId", companyId)
开发者_StackOverflow .SetInt64("arId", areaId);
IList<SpecialProduct> specialProducts = query.List<SpecialProduct>();
When the 2nd statement above executes, I get an error stating:
Could not execute query[SQL: SQL not available] The value "SpecialProduct" is not of type "MyNamespace.DomainModel.SpecialProduct" and cannot be used in this generic collection.
Parameter name: value(Note that the object shows in the message above as "SpecialProduct" because of a ToString() override in the SpecialProduct class.)
If I change the statement to return a list of the superclass, Product, like so...
IList<Product> products = query.List<Product>();
...then I don't get the error and a single matching object is returned in the list. Examining this object in the debugger I see that appears to be, in fact, a SpecialProduct according to the ToString() override, but looking closer I see that it is an NHibernate proxy class. If I try casting the object to SpecialProduct, the cast fails. Hmmm...
I also checked in the database itself and confirmed that the record was saved as a SpecialProduct (based on the fact that there is a matching record in the joined-subclass table).
I need to get the results as a generic collection of SpecialProperty objects.
Any ideas on why this isn't working?
This is by design. NH proxies inherit from the base type, not subclasses.
Hopefully, this link will help.
精彩评论