This project is read-only.

Building searches with EF

Apr 11, 2013 at 11:47 PM

I am using EF with 2012. In my research, I have found a number of ways to build a search string (say if we give the user a number of options to search on.) I am trying to figure out which is the best approach to use, given the changes in EF over time.

Say I allow my users to enter a contacts first name, last name, company name, and/or area code.

I want to check what was passed in the request object and only search on those values provided.

The code I have now (simplified) is:
var response = new SearchCategoriesResponse();
NorthwindEntities ctx = new NorthwindEntities();
System.Linq.IQueryable<Category> entity = ctx.Categories;
if (request.CategoryID > 0)
    entity = entity.Where(inc => inc.CategoryID == request.CategoryID);
if (!string.IsNullOrEmpty(request.CategoryName))
    entity = entity.Where(cat => EntityFunctions.Left(cat.CategoryName, request.CategoryName.Length) == request.CategoryName);
response.Success = entity.Count() > 0;
// Code to populate and return response properties below
Is this really the best way to build an EF query with variable filtering criteria? It works and I don't think the actual query is run until I do the Count(). But given the evolution of EF over the years, I thought I would check before I wrote too much code - especially because I have found a number of alternatives on the web and am not sure which is better or why.

Any suggestions, links, etc. would be greatly appreciated.
Apr 26, 2013 at 6:13 PM
Looks like a workable approach to me, but to be honest, I am not an EF guy.