i am trying to apply an expression filter dynamically and can’t get it working. Would any of you guys know, how can apply the given expression filter inside the for each loop and then return the object of Type t when it matches?
Public Function FindByCondition( _
filter As Expressions.Expression(Of Func(Of T, Boolean))) As T Implements IRepository(Of T).FindByCondition
Dim metaData As New LinqMetaData
AutoMapper.Mapper.CreateMap(GetType(EntityType), GetEntityType)
Dim dataSource = TryCast(metaData.GetQueryableForEntity(CInt([Enum].Parse(GetType(EntityType), GetEntityType.Name))), IQueryable(Of EntityBase))
Dim q = (From p In dataSource _
Select p).ToList
Dim g = AutoMapper.Mapper.Map(Of IEnumerable(Of T))(q)
For Each k As T In g
k.Equals(filter)
Next
End Function
You need to compile the expression tree to a delegate, then call the delegate on each instance.
Or, more simply,
Or, much more simply,
This will actually run the filter on the server (or whatever your
IQueryableimplementation does).For all of the other cases, you should accept a
Func(Of T, Boolean)rather than an expression tree, since you don’t actually need the expression tree.Compile()is an expensive call.