polymorphic hql
        Posted  
        
            by 
                Berryl
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Berryl
        
        
        
        Published on 2011-01-08T15:08:25Z
        Indexed on 
            2011/01/17
            6:53 UTC
        
        
        Read the original article
        Hit count: 388
        
nhibernate
|hql
I have a base type where "business id" must be unique for a given subclass, but it is possible for there to be different subclasses with the same business id.
If there is a base type with a requested id but of the wrong subclass I want to return null, using a named query. The code below does this, but I am wondering if I can avoid the try/catch with a better HQL. Can I?
Cheers,
Berryl
current hql
<query name="FindActivitySubjectByBusinessId">
<![CDATA[
          from ActivitySubject act 
          where act.BusinessId = :businessId 
]]>
</query>
current fetch code
    public ActivitySubject FindByBusinessId<T>(string businessId) where T : ActivitySubject
    {
        Check.RequireStringValue(businessId, "businessId");
        try {
            return _session.GetNamedQuery("FindActivitySubjectByBusinessId")
                .SetString("businessId", businessId)
                .UniqueResult<T>();
        }
        catch (InvalidCastException e) {
            // an Activity Subject was found with the requested id but the wrong type
            return null;
        }
    }
© Stack Overflow or respective owner