Mark Gilbert's Blog

Science and technology, served light and fluffy.

Sorry, you’re just not my Type

I was trying to write a method for one of my Castle ActiveRecord classes that would return a list of Contributors by type.  The types were defined as an Int32 enumeration in the Contributor class, and my original method was as follows:

Public Shared Function GetAllByType(ByVal SearchContributorType As ContributorType) As IList(Of Contributor)
    Dim MySearchCriteria As DetachedCriteria
    Dim MySearchOrder As NHibernate.Expression.Order
    Dim ContributorArray() As Contributor
    Dim ContributorCollection As ICollection(Of Contributor)

    MySearchCriteria = DetachedCriteria.For(GetType(Contributor)).Add(Expression.Eq("Type", SearchContributorType))
    MySearchOrder = New NHibernate.Expression.Order("Name", True)
    ContributorArray = Contributor.FindAll(MySearchCriteria, MySearchOrder)

    ContributorCollection = CType(ContributorArray, ICollection(Of Contributor))
    Return CType(ContributorCollection, IEnumerable(Of Contributor))
End Function

When I ran the unit test that exercised the FindAll method, I got this error:

Could not perform FindAll for Contributor

Not terribly helpful, but when I looked at the inner exception, I found the real cause:

Type mismatch in NHibernate.Expression.EqExpression: Type expected type System.Int32, actual type BMSBusinessServices.Contributor+ContributorType

I tried explicitly casting the SearchContributorType parameter to an Integer (Int32) value, and it worked – no more exception, and my test passed.  

In the past, .NET has done a fabulous job of implicitly casting things for me.  Perhaps what is happening here (and I have not looked at the NHibernate source to confirm this, so this is pure conjecture) is that NHibernate needed to compare the Contributor.Type property to the SearchContributorType variable.  The former is declared as Int32 while the latter was of the Contributor.ContributorType enumeration.  Even though the latter was also ultimately defined as Int32, NHibernate needed to do something like a .Equals, and the slight difference in types was just enough to throw it off.

At any rate, the CType() was easily inserted into the Expression, and I was on my merry way.

Advertisements

January 7, 2010 - Posted by | Castle ActiveRecord, Visual Studio/.NET

Sorry, the comment form is closed at this time.

%d bloggers like this: