2

I have a number of calls for the same query but with slightly different WHERE clause, does anyone know if it's possible to pass a variable as the column name as I can't seem to acheive it.

I know the below isn't correct but just to give you an idea of what i'm trying to acheive.

public EmailUserListViewModel EmailUserListData(int CaseId, string ColumnName)
{
    CaseId = CaseId,
    EmailUserList = (from u in efContext.PgsUsers
                        where ColumnName == true
                        orderby u.FirstName, u.LastName
                        select new EmailUserListModel
                        {
                            UserId = u.Id,
                            Name = ((u.FirstName == null) ? "" : u.FirstName) 
                                   + ((u.LastName == null) ? "" : " " + u.LastName),
                            Email = u.Email,
                            Checked = false

                        }).ToList()
    };
}
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
Jammer
  • 2,330
  • 11
  • 48
  • 77
  • 5
    Possible duplicate of [Dynamic WHERE clause in LINQ](http://stackoverflow.com/questions/848415/dynamic-where-clause-in-linq) – Nico Jan 19 '17 at 12:44
  • You need to use the 'u' variable in the Where. So something like u == ColumnName – jdweng Jan 19 '17 at 12:48

2 Answers2

2

I suppose you could use Reflection to dynamically retrieve the value of the property

from u in efContext.PgsUsers where (typeof(PgsUser).GetProperty(ColumnName).GetValue(u) as bool) == true

or

from u in efContext.PgsUsers where (u.GetType().GetProperty(ColumnName).GetValue(u) as bool) == true
Zaphod Fox
  • 58
  • 1
  • 8
  • I've tried something similar to this and get the same error for them: `'System.Reflection.PropertyInfo GetProperty(System.String)' has no supported translation to SQL.` – Jammer Jan 19 '17 at 13:03
  • The Reflection filter is not SQL compatible, you have to apply it to a ToList()ed version of your query. – Zaphod Fox Jan 19 '17 at 13:09
1

You could write such method:

public Expression<Func<T, bool>> getExpression<T>(string columnName)
{
    var param = Expression.Parameter(typeof(T));
    var equal = Expression.Equal(Expression.Property(param, columnName), Expression.Constant(true));
    return (Expression<Func<T, bool>>)Expression.Lambda(equal, param);
}

and use it in where:

where getExpression<YourType>("ColumnName")
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49