2009-08-25 23 views
0

我有下面的代碼拋出一個異常(下面的代碼註釋中的細節)。我只是試圖將一個枚舉的實例作爲Where子句的一部分。我理解這個消息,但我不明白爲什麼EF無法解析Int32枚舉。使用基於實體框架中的Where子句中的枚舉的var拋出異常

它的作品,如果我複製枚舉到一個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更優雅的解決方案?

回答

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

+0

一個蹩腳的bug,它的位:

一些更多的信息可以在這裏找到。謝謝。 – 2009-08-25 13:03:32

相關問題