Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
            .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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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:

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading