How can I make a dynamic lambda expression from a string?

I need to use a Lambda expression in my method

public static class QueryableDynamicExtension
{
    public static IQueryable<T> DynamicEquals<T>(
       this IQueryable<T> query,
       string field,
       object value)
    {
        Expression<Func<T, bool>> expr = ???                   

        return query.Where(expr);
    }
}

In this method, I want it to return just like

IQueryable<Article> articles = new ModelDataContext().Articles.Where(m => m.CategoryId == 5);
// I want replace by
IQueryable<Article> articles = new ModelDataContext().Articles.DynamicEquals("CategoryId", 5);

How do I build "expr" in this case? Please, help.

+3
source share
1 answer

You can look at the Dynamic LINQ library as posted on Scott Gu's blog here . I used this earlier when I created a rule-based product system for work and used dynamic expressions stored at our database level to provide additional expressions for filtering product sets.

+2
source

Source: https://habr.com/ru/post/1762037/


All Articles