Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF: How to pass column name dynamically to where clause

i am not before dev pc. i just started working with EF. so curious to know can we pass column name dynamically for where clause.

see a screen shot for searching grid.

enter image description here

i just compose a sample query. please tell me does it work?

public ActionResult Index(String ColumnName,String SearchText)
{

    private CustomersEntities db = new CustomersEntities();

    var customer = (from s in db.Customers
                    select new CustomerDTO
                    {
                    CustomerID = s.CustomerID,
                    CompanyName = s.CompanyName,
                    ContactName = s.ContactName,
                    ContactTitle = s.ContactTitle,
                    Address = s.Address
                    })
    .Where(s => s.Field<string>(ColumnName).ToUpper().Contains(SearchText.ToUpper());

    return View(customer);

}

thanks

like image 321
Monojit Sarkar Avatar asked Dec 19 '25 07:12

Monojit Sarkar


1 Answers

public ActionResult Index(string ColumnName, string SearchText)
{
    var arg = Expression.Parameter(typeof(Customer), "x");

    var strType = typeof(string);
    var ToUpperMeth = strType.GetMethods().Where(x => x.Name == nameof(string.ToUpper) 
                                          && x.GetParameters().Count() == 0).Single();
    var ContainsMeth = strType.GetMethods().Where(x => x.Name == nameof(string.Contains) 
                                          && x.GetParameters().Count() == 1).Single();

    var exprVal = Expression.Constant(SearchText);
    var toUpExprVal = Expression.Call(exprVal, ToUpperMeth);

    var exprProp = Expression.Property(arg, ColumnName);
    var toUpExpr = Expression.Call(exprProp, ToUpperMeth);
    var contExpr = Expression.Call(toUpExpr, ContainsMeth, toUpExprVal);

    var predicate = Expression.Lambda<Func<Customer, bool>>(contExpr, arg);

    var customer = (from s in db.Customers
                    select new CustomerDTO
                    {
                        CustomerID = s.CustomerID,
                        CompanyName = s.CompanyName,
                        ContactName = s.ContactName,
                        ContactTitle = s.ContactTitle,
                        Address = s.Address
                    }).Where(predicate).ToList();

    return View(customer);
}
like image 181
Slava Utesinov Avatar answered Dec 21 '25 23:12

Slava Utesinov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!