Home > Enterprise >  How to apply expression inside expression dynamically?
How to apply expression inside expression dynamically?

Time:05-21

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
            .Include(a=>a.Profile)
            .ThenInclude(p=>p.ProfileEmployer)
            .ThenInclude(p=>p.Employer)
            .Include(a=>a.ProfileApplicationDetail)
            .ThenInclude(p=>p.ApplicationStatusSysCodeUnique)
            .Include(a=>a.Person)
            .ThenInclude(p=>p.PersonDetail)
            .Include(a=>a.JobSpecification)
            .ThenInclude(j=>j.JobSpecificationDetail)
            .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?

CodePudding user response:

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

builder
    .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));
  • Related