Pinx0
Pinx0

Reputation: 1258

Query only base class

Having the following structure:

Article is not abstract, some items are just articles, other are derived types. Here's my NHibernate config, following table-per-hierarchy strategy (because subclases are also on the main table, and may or may not contain aditional data in other tables):

<class name="IArticle" table="Articles" >
<id name="Id" column="IdArticle"/>
 <discriminator type="string" formula="(CASE WHEN IdTipoDef LIKE 'DefProd8' THEN 'SUPER' ELSE CASE WHEN IdTipoDef LIKE 'DefProd9' THEN 'AWESOME' ELSE  'ARTICLE' END END)"/>
<property name="Description" column="Descrip"/>
<subclass name="SuperArticle" discriminator-value="SUPER">
    <join table="otherTable">
        ...
    </join>
</subclass>
<subclass name="AwesomeArticle" discriminator-value="AWESOME">
    <join table="otherOtherTable">
      ...
    </join>
</subclass>
<subclass name="Article" discriminator-value="ARTICLE">
</subclass>
</class>

The problem is when I try to query the ones that are just Article, that it returns also its subclasses, and if I try to count I get an error:

 [TestMethod]
    public void EncuentraArticulosTest()
    {
        ISession session = NHibernateHelper.GetSession();
        session.BeginTransaction();
        Debug.Write(session.QueryOver<Article>().Where(a => a.GetType() == typeof(Article)).RowCount());
        Assert.IsTrue(session.QueryOver<Article>().RowCount() > 0);
        session.Close();
    }

This (either the Assert or the Debug) gives the following exception:

Seguimiento de la pila de Result:   
en NHibernate.Impl.AbstractQueryImpl.UniqueElement(IList list)
en NHibernate.Impl.CriteriaImpl.UniqueResult[T]()
en NHibernate.Criterion.QueryOver`1.SingleOrDefault[U]()
en NHibernate.Criterion.QueryOver`1.NHibernate.IQueryOver<TRoot>.RowCount()
en MyCompany.Test.NHibernateTests.EncuentraArticulosTest() en ...\NHibernateTests.cs:línea 36
Mensaje de Result:  
El método de prueba MyCompany.Test.NHibernateTests.EncuentraArticulosTest produjo la excepción: 
NHibernate.NonUniqueResultException: query did not return a unique result: 7

Upvotes: 0

Views: 517

Answers (2)

Pinx0
Pinx0

Reputation: 1258

Finally I found this answer from Java's version (Hibernate):

How to perform a non-polymorphic HQL query in Hibernate?

Upvotes: 0

Fran
Fran

Reputation: 6520

This happens by design because your derived classes are base types. This is classic object oriented polymorphism.

See this ticket if you really need to get only base class entities back.

NHibernate: Load base class objects only

Upvotes: 1

Related Questions