baaroz
baaroz

Reputation: 19587

Entity Framework dynamic linq where from generic source with dynamic where clause

I am trying to query Entity Framework where clause statement with generic type when table name is not known.

I am trying to use dynamic linq:

public static IEnumerable<T> wherePost<T>(this IEnumerable<T> source,
            string predicate) where T : class
{    
    using (var context = new dbEntities())
    {
        string exp = predicate;//driverId>3
        var p = Expression.Parameter(typeof(T));
        var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, exp);    
    }
}

This is the call example to wherePost

 db.Drivers.wherePost("City == \"Paris\"");

Not sure how to continue and query the DbSet<T> from Entity Framework using the DynamicExpression.

Upvotes: 1

Views: 359

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27366

I assume you do not need to change TableName on the fly, but just query table via filter.

public static IQueryable<T> wherePost<T>(this IQueryable<T> source,
    string predicate) where T : class
{    
    string exp = predicate;//driverId>3
    var p = Expression.Parameter(typeof(T));
    var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, exp);    
    var whereExpr = Expression.Call(typeof(Queryable), nameof(Queryable.Where), new[] { typeof(T) }, source.Expression, e);

    return source.Provider.CreateQuery<T>(whereExpr);
}

And usage:

db.Drivers.wherePost("City == \"Paris\"").ToList();

Upvotes: 1

Related Questions