How to apply expression inside expression dynamically?


So, I have property, which is an expression.

public Expression<Func<Profile, bool>> ManagerFilter { get; set; }

Next, I want to implement this filter, which is the expression above dynamically here:

var queryTest = applicantCacheRepo
            .FirstOrDefaultAsync(a=>a.Profile == filters.ManagerFilter)

What I am trying to do here is to apply a filter for Profile in this query dynamically. The problem is that I do not know the exact property of Profile according to which it is going to be filtered.

Question is: how can I implement this filter dynamically here?

>Solution :

You can do that only with help from third party libraries. I would suggest to use LINQKit. It needs just configuring DbContextOptions:

    .UseSqlServer(connectionString) // or any other provider
    .WithExpressionExpanding();     // enabling LINQKit extension

Then you can use your filter via Invoke extension:

var queryTest = await
   .FirstOrDefaultAsync(a => filters.ManagerFilter.Invoke(a.Profile));

Leave a Reply Cancel reply