Racheli
Racheli

Reputation: 111

add where clauses to linq query with generic column name

I want to add where clauses to a linq query only if there is the column on the generic type table.

code example : this function is generic for all tables in model. I want to add where condition for all the tabels that have "AccountId" column.

public IQueryable RetrieveAll(params Expression>[] eagerProperties) { 
var entitySet = ResolveEntitySet(typeof(T));
var query = context.CreateQuery<T>(entitySet);
foreach (var e in eagerProperties)
{
     query = query.Expand(e);
} 
var type = typeof(T); 
var account =    type.GetProperty("AccountId"); 
if(account!=null) 
  { 
    query = query.where(x=>x...) 
  } 
return query

I need something like

Guid g = new Guid("3252353h....")
query.where(x=>x.AccountId == g)

Thanks

Upvotes: 3

Views: 777

Answers (1)

Alberto Monteiro
Alberto Monteiro

Reputation: 6219

You must create the Where predicate dynamically using Expression Tree, look code below:

public static IQueryable<T> RetrieveAll<T>(params Expression[] eagerProperties)
{
    var type = typeof(T);
    var entitySet = ResolveEntitySet(type);
    var query = context.CreateQuery<T>(entitySet);
    foreach (var e in eagerProperties)
    {
        query = query.Expand(e);
    }
    var account = type.GetProperty("AccountId");
    if (account != null)
    {
        Guid g = new Guid("3252353h....");
        var parameter = Expression.Parameter(type);
        var property = Expression.Property(parameter, account);
        var guidValue = Expression.Constant(g);

        var lambdaPredicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(property, guidValue), parameter);
        return query.Where(lambdaPredicate);
    }
    return query;
}

Upvotes: 4

Related Questions