How to build up a Linq to Sql where clause bit by

2020-08-14 10:09发布

问题:

I am being passed a set of querystring parameters within a Parameters class with which to query an image database. With each call some parameters may by null. So in sql I would build up the query like

if (parameters.Value1 != null)
{
    sql.Append("sql_where_clause");
}

if (parameters.Value2 != null)
{
    sql.Append("sql_where_clause");
}

How do I do the same using Linq?

回答1:

easy, IQueryables aren't evaluated until you enumerate, so simply keep tagging on where clauses.

if (parameters.Value1 != null)
{
    results = results.Where(x => <some condition>);
}

if (parameters.Value2 != null)
{
    results = results.Where(x => <some other condition>);
}


回答2:

The best way to dynamically build where-clauses is to use the wonderful Albahari PredicateBuilder.

You can use this to build where-clause expressions containing OR as well as AND. Language-integrated support for this was originally intended but didn't quite make it into C# 3.

For example:

var whereClause = PredicateBuilder.False<Customer>();

if (parameters.Value1 != null)
{
    whereClause = whereClause.Or(customer => customer.City == parameters.Value1);
}

var query = db.Customers.Where(whereClause);