views:

247

answers:

1

I have the following code which throws an exception (detail in code comments below). I am merely trying to use an instance of an enum as part of the Where clause. I understand the message, but I don't understand why EF cannot parse an Int32 enum.

It works if I copy the enum to an Int32 and then filter on that, but it seems very messy.

    Enum MyEnum As Int32
    Zero
    One
    Two
End Enum
Shared Function GetStuff(ByVal EnumValue As MyEnum) As IQueryable
    Dim Db As New MainDb
    Dim DetailList As IQueryable
    Dim MyInt As Int32 = EnumValue

    ' PostalProviderId is an Int column in SQL.
    'DetailList = From D In Db.DeliveryService Where D.PostalProviderId = EnumValue ' This fails.
    DetailList = From D In Db.DeliveryService Where D.PostalProviderId = MyInt ' This works.

    ' The following attempt to enumerate the results yields;
    ' **** System.NotSupportedException was unhandled by user code
    ' **** Message = "Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."
    ' **** Source = "System.Data.Entity"
    For Each Thingy In DetailList
        Console.WriteLine(Thingy.ToString())
    Next
    Return DetailList

End Function

Is there a more elegant solution than copying the enum values to a local int?

+3  A: 

The problem is that the entity framework doesn't know how to eveluate your enum when it is building the T-SQL to get the int behind it. The short answer is that you have to store it in a temp variable and use that.

Some more information can be found at:

http://gmontrone.com/post/problem-with-casting-enums-in-linq-to-entities.aspx

and

http://www.matthidinger.com/archive/2008/02/26/entity-framework-comparison-frustration-explained.aspx

Nathan W
Bit of a naff bug that. Thanks.
Ryan ONeill