Vb.net 实体框架4的扩展方法

Vb.net 实体框架4的扩展方法,vb.net,linq,entity-framework,expression-trees,Vb.net,Linq,Entity Framework,Expression Trees,我使用实体框架实体的扩展方法: <Extension()> Public Function IsExcluded(ByVal item As AnomalyProduct) As Boolean Dim result As Boolean If (item.WholesalerProductCode IsNot Nothing) AndAlso (item.WholesalerProductCode = _excludedChar)

我使用实体框架实体的扩展方法:

    <Extension()>
    Public Function IsExcluded(ByVal item As AnomalyProduct) As Boolean

        Dim result As Boolean

        If (item.WholesalerProductCode IsNot Nothing) AndAlso (item.WholesalerProductCode = _excludedChar) Then
            result = True
        Else
            result = False
        End If

        Return result

    End Function
但通过这种方式,我需要从数据库加载所有异常产品。最终得到一个布尔值需要很长时间

我认为表达式树可以帮助我,但我无法做到这一点


我们将非常感谢您的帮助。

您只能通过内存中的数据来实现这一点。 当您在Where(或任何其他)子句中放入一些linq时,实体框架将把它转换为T-SQL

无法将其转换为任何t-SQL:

repo.AnomalyProducts.Where(Function(p) p.IsExcluded).Any
这可以(因为您正在内存中获取所有数据:

repo.AnomalyProducts.ToList.Where(Function(p) p.IsExcluded).Any
为了减少工作量,您可以创建一个表达式(这是Where子句所期望的)并使用它。这只会减少您必须复制和粘贴代码的位置

Dim exp As Expression(Of Func(Of AnomalyProduct, Boolean)) = Function(a) Not String.IsNullOrEmpty(a.WholesalerProductCode) AndAlso a.WholesalerProductCode <> _excludedChar
repo.AnomalyProducts.Where(exp).Any
Dim exp As Expression(Of Func(Of AnomalyProduct,Boolean))=函数(a)不是字符串。IsNullOrEmpty(a.whistalerproductcode)和also a.whistalerproductcode _excludedChar
回购异常产品,其中(exp).Any

我还没有测试过它,但它应该可以正常工作。

为什么不做
repo.AnomalyProducts.Where(Function(p)p.Where批发商产品代码=_excludedChar)。Any()
?@Arnold,因为排除标准将来可能会改变,排除测试“被排除”调用程序中的多个点。因此,当critera发生更改时,我不希望读取所有代码来跟踪它。如果您愿意,也可以让您的
IsExclude
方法返回上述表达式。@Jessehowing您将如何使用它?
。Where(SomeClass.IsExclude())
?这感觉不对。当它在同一个类中时,可以使用
。Where(x=>isExclude(x))
,甚至可能是
。Where(isExclude)
。您还可以创建一个具有适当名称的类,例如
ProductFunctions
,并使用
ProductFunctions。正如您所建议的那样,IsExclude
。重要的是返回表达式,而不是结果本身。
Dim exp As Expression(Of Func(Of AnomalyProduct, Boolean)) = Function(a) Not String.IsNullOrEmpty(a.WholesalerProductCode) AndAlso a.WholesalerProductCode <> _excludedChar
repo.AnomalyProducts.Where(exp).Any