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?
4 Answers
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)
{
// ...
}
2 Comments
Jeremy
Will the original definition of "query" cause "select * from products" to be executed?
kevingessner
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.
You might take a look at this article about dynamically generating lambda expression objects to do it.