我有一个基类型,其中“业务ID”对于给定的子类必须是唯一的,但是可能存在具有相同业务ID的不同子类。
如果存在具有请求的id但是子类错误的基类型,我想使用命名查询返回null。下面的代码执行此操作,但我想知道是否可以避免使用更好的HQL的try / catch。我可以吗?
干杯,
Berryl
<query name="FindActivitySubjectByBusinessId">
<![CDATA[
from ActivitySubject act
where act.BusinessId = :businessId
]]>
</query>
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;
}
}