I'm implementing a search feature for an app that uses entity framework. There are several optional fields for searching a particular database table/view. What is the best way to implement such a search with EF? Stored procedure? Or can it be done (realistically) using Linq only?
+1
A:
You should be able to do this in LINQ easily enough. Always remember that LINQ queries are chainable:
var query = (from p in products
select p);
if(field1 != null)
{
query = (from p in query
where p.Field1 = field1
select p);
}
if(field2 != null)
{
query = (from p in query
where p.Field2 = field2
select p);
}
foreach(Product p in query)
{
// ...
}
LorenVS
2009-08-25 17:47:37
Will the original definition of "query" cause "select * from products" to be executed?
Jeremy
2009-08-25 17:57:32
No. LINQ queries are not enumerated (i.e. the results are not retrieved from the DB) until the last possible moment. The calls just build up, then when you need to access a specific element in the result (or the count, etc.), the whole assembled query is retrieved from the DB.
kevingessner
2009-08-25 18:02:43
+1
A:
What Loren says will work (+1). Or use Microsoft Dynamic LINQ. It works fine with L2E.
Craig Stuntz
2009-08-25 17:55:05
A:
You might take a look at this article about dynamically generating lambda expression objects to do it.
Jason Jackson
2009-08-25 18:01:54
+2
A:
A common pattern for handling optional search parameters is to do something like this:
string p = null;
var q = from o in dataContext.Products
where ((o.Name == p) || (p == null))
select o;
Andrew Peters
2009-08-25 18:11:09