Dynamic column in where condition

c# dynamicquery expression-trees linq

Question

In my scenario, i want to query a table with a user selected column name. So every time column name for where condition will change, so I am trying to query on a query with lambda.

I exactly don't know how to do this, Please help me out of this. Or suggest if there is any other way to do this?

string[] criteria = searchCriteria.Split('_');
var columnName = criteria[0];                        
var columnValue = criteria[1];

var subQry = (from e in ctx.tblEmployee
              where (e.DateOfJoining <= startDate || (e.DateOfJoining.Value.Month == ApplyMonth && e.DateOfJoining.Value.Year == ApplyYear)) &&
                    monInputEmployee.Contains(e.Id) == flag
              select new
              {
                  e.Id,
                  e.Code,
                  e.FName,
                  e.DateOfJoining
              }).ToList();

var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");
var comparison = Expression.And(
                 Expression.Equal(Expression.Property(eParam, columnName), Expression.Constant(columnValue)),
                 Expression.Equal(Expression.Property(eParam, "CompId"), Expression.Constant(compId)));

var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(comparison, eParam);
var mainQry = subQry.Where(lambda);
1
2
2/18/2015 8:20:33 AM

Popular Answer

This is How i solved it, Just added one extra Where with lambda :-

string[] criteria = searchCriteria.Split('_');
var columnName = criteria[0];                        
var columnValue = criteria[1];

var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");
var comparison = Expression.Equal(Expression.Property(eParam, columnName), Expression.Convert(Expression.Constant(columnValue), Expression.Property(eParam, columnName).Type));

var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(comparison, eParam);

var subQry = (from e in ctx.tblEmployee
              where (e.DateOfJoining <= startDate || (e.DateOfJoining.Value.Month == ApplyMonth && e.DateOfJoining.Value.Year == ApplyYear)) &&
                    monInputEmployee.Contains(e.Id) == flag
              select new
              {
                  e.Id,
                  e.Code,
                  e.FName,
                  e.DateOfJoining
              }).Where(lambda)
                .ToList();
2
2/24/2015 1:08:40 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow