简体   繁体   中英

ASP.NET MVC custom LINQ query

I'd like to make an custom database query in ASP.NET MVC 5.

I have a filtering form which is having an option to choose a column from the drop down list and then type in search phrase in the text box, after hitting search button supposed to show results from sql database.

My form is ready, all the variables are set I just have a difficulties with building this kind of query :

"SELECT * FROM table WHERE "+ dropDownListResult +" = " + searchStringFromTxtBox +" ";

I tried couple of different options but none work way I expected.

 qry = from a in db.Table
    where dropDownListResult == searchStringFromTxtBox                
    select a;

or

qry = qry.Where(s => s.Equals(dropDownListResult).Contains(searchStringFromTxtBox));

I know it's probably a dummy question but I lost enough time looking for the answer.

Please point me into proper direction.

You'd have to create Expression Tree and pass it to Where method:

public static Expression<Func<TEntity, bool>> GetPropertyEqualityExpression<TEntity, TProperty>(string propertyName, TProperty propertyValue)
{
    var parameter = Expression.Parameter(typeof(TEntity));
    var property = Expression.Property(parameter, propertyName, null);
    var equality = Expression.Equal(property, Expression.Constant(propertyValue));
    var lambda = Expression.Lambda<Func<TEntity, bool>>(equality, parameter);
    return lambda;
}
var condition = GetPropertyEqualityExpression<MyClass, string>(dropDownListResult, searchStringFromTxtBox)
var qry = source.Where(condition);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM