实体框架Where方法参数

时间:2011-04-12 09:51:10

标签: entity-framework-4 where

以下EF语句无法编译,因为它需要2个额外的参数,一个int和一个bool。我无法弄清楚如何提供它们或它们用于什么。

Dim L2 = Db.SecurityLogs.Where(Function(x) x.OrderId = OrderId)

编译错误是;

Error   27  Overload resolution failed because no accessible 'Where' can be called with these arguments:
'Public Function Where(predicate As String, ParamArray parameters() As System.Data.Objects.ObjectParameter) As System.Data.Objects.ObjectQuery(Of SecurityLog)': Lambda expression cannot be converted to 'String' because 'String' is not a delegate type.
Extension method 'Public Function Where(predicate As System.Func(Of SecurityLog, Integer, Boolean)) As System.Collections.Generic.IEnumerable(Of SecurityLog)' defined in 'System.Linq.Enumerable': Nested function does not have a signature that is compatible with delegate 'System.Func(Of SecurityLog, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Func(Of SecurityLog, Boolean)) As System.Collections.Generic.IEnumerable(Of SecurityLog)' defined in 'System.Linq.Enumerable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of SecurityLog, Integer, Boolean))) As System.Linq.IQueryable(Of SecurityLog)' defined in 'System.Linq.Queryable': Nested function does not have a signature that is compatible with delegate 'System.Func(Of SecurityLog, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of SecurityLog, Boolean))) As System.Linq.IQueryable(Of SecurityLog)' defined in 'System.Linq.Queryable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'.  D:\Projects\OutdoorAndCountry\trunk\Source\Server\DataModel\SecurityLogDb.vb    24  22  DataModel

我以为我理解了如何使用Where方法,所以我必须以通常的方式调用它,而MSDN似乎只是指没有参数传递函数。

我错过了什么?

提前致谢,

赖安

1 个答案:

答案 0 :(得分:2)

我认为编译器错误消息中的最后一行(代表应该应用的相关重载)是重要的提示:

  

扩展方法'公共功能   在哪里(谓词As   System.Linq.Expressions.Expression(中   System.Func(Of SecurityLog,Boolean)))   作为System.Linq.IQueryable(Of   SecurityLog)'定义于   'System.Linq.Queryable':Option Strict   不允许隐含的转换   “布尔?到'布尔'。

它表示在您的表达式x.OrderId = OrderId中,左侧(SecurityLog类的OrderId属性)是可以为空的int(Integer?),或者右侧的类型是可以为空的int。可空和不可空整数的比较导致可空的布尔(Boolean?)。编译器抱怨它无法将此Boolean?转换为lambda表达式所需的非可空Boolean

要解决此问题,您可以将可空类型中可能的Nothing值转换为0(或其他一些整数):

' If x.OrderId is the nullable Integer
Dim L2 = Db.SecurityLogs.Where(Function(x) If(x.OrderId, 0) = OrderId)

' If OrderId is the nullable Integer
Dim L2 = Db.SecurityLogs.Where(Function(x) x.OrderId = If(OrderId, 0))

(如果不是100%确定VB语法,但If(x, y)应该在C#中对应x ?? y,那么:如果x为Nothing则返回y,否则返回x的值。)< / p>

您也可以在VB编译器或项目设置中关闭严格打开选项,因为只有在打开选项时才会出现此错误。 (但是,我猜可能还有一些其他原因可以在项目中使用此选项,因为它是非默认选项。)