【问题标题】:Using a var based on an enum in a Where clause in Entity Framework throws an exception在实体框架的 Where 子句中使用基于枚举的 var 会引发异常
【发布时间】:2009-08-25 11:15:14
【问题描述】:

我有以下引发异常的代码(下面的代码 cmets 中有详细信息)。我只是想使用枚举的一个实例作为 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 更优雅的解决方案?

【问题讨论】:

    标签: .net entity-framework enums where-clause


    【解决方案1】:

    问题是实体框架在构建 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

    【讨论】:

    • 有点小错误。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 2010-11-08
    • 2011-05-11
    相关资源
    最近更新 更多