Reputation: 359
I use an extension method for entity Framwork entity:
<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
I want to get a list of entity depending of the Extension Method result:
Private Function HasPacksExcluded(ByVal contextId As Guid) As Boolean
Dim result As Boolean
Dim context As ContextManager.ContextData
Dim repo As ILancelotLabEntities
context = _context.GetContext(contextId)
repo = context.RepositoryContext
result = repo.AnomalyProducts.ToList.Where(Function(p) p.IsExcluded).Any
Return result
End Function
But by this way i need to load all AnomalyProducts from Database. It take a long time just to get finally a boolean.
I think Expression Tree can help me, but i am not able to do that.
some help will be appreciated.
Upvotes: 1
Views: 313
Reputation: 1136
You can only do that with data on memory. When you put some linq inside the Where (or any other) clause, entity framework will translate that to T-SQL.
This can't be translated to any T-SQL:
repo.AnomalyProducts.Where(Function(p) p.IsExcluded).Any
This can (because you're getting all data in memory:
repo.AnomalyProducts.ToList.Where(Function(p) p.IsExcluded).Any
To minimize effort, you could create a Expression (that is what the Where clause expects) and use that. This will only minimize the amount of places you'll have to copy and paste your code.
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
I havent tested it, but it should work just fine.
Upvotes: 2