0

我有以下引发异常的代码(下面的代码注释中的详细信息)。我只是想使用枚举的一个实例作为 Where 子句的一部分。我理解该消息,但我不明白为什么 EF 无法解析 Int32 枚举。

如果我将枚举复制到 Int32 然后对其进行过滤,它会起作用,但它看起来很混乱。

    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

有没有比将枚举值复制到本地 int 更优雅的解决方案?

4

1 回答 1

3

问题是实体框架在构建 T-SQL 以获取其背后的 int 时不知道如何评估您的枚举。简短的回答是你必须将它存储在一个临时变量中并使用它。

可以在以下位置找到更多信息:

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

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

于 2009-08-25T12:48:49.937 回答