Disadvantages of building searches with Linq to Entities? RRS feed

  • Question

  • I'm implementing a data service which includes a method for specifying a search for a particular business entity.  This means that the output type is always the same (a list of the business objects), but the where clauses are built dynamically based upon the data provided in a 'search' object.

    To avoid having to mess around with strings in ObjectQuery, I've implemented this using Linq to Entities by appending 'Where' methods to a basic IQueryable reference created from selecting all data in the table:

    public List<Person> PeopleSearch(PeopleSearchParameters search) 
        IQueryable<People> queryConstruct = entityContext.Person.Include("Address").Select(d => d); 
        // Where clauses 
        // Last Name 
        if (!String.IsNullOrEmpty(search.LastName)) 
            queryConstruct = queryConstruct.Where(d => d.LastName == search.LastName); 
        // First Name 
        if (!String.IsNullOrEmpty(search.FirstName)) 
            queryConstruct = queryConstruct.Where(d => d.FirstName == search.FirstName); 
        // City 
        if (!String.IsNullOrEmpty(search.City)) 
            queryConstruct = queryConstruct.Where(d => d.Address.City == search.City); 
        return queryConstruct.ToList(); 

    I haven't seen this approach used anywhere else, but it seems to work perfectly, giving me a dynamically built where clause as well as design time type checking.  Can anyone tell me if I'm going to have any problems with this approach?

    Tuesday, February 17, 2009 10:54 AM


  • If you don't need a lot of flexibility, and you have total control over the search parameters and you don' t mind coding the various if statements, I don't see a problem with this.

    I have a client that has a much more complex search engine and they were thrilled when I showed them the benefits (in their scenario) of using Entity SQL instead of LINQ to Entities.

    • Marked as answer by AntFarmer Tuesday, February 17, 2009 5:20 PM
    Tuesday, February 17, 2009 4:35 PM