Friday 21 February 2014

Searching Model Data based on string and integer field types

Scenario

You need to add a search function based on model data based on searching both string and int datatypes. If you try the obvious method in your LINQ query as just converting your int field ToString you end up with an error similar to this:

ToString is not supported in linq to entities

Or even this bad boy:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

After trawling around the forums for a good hour or so I found the following solution. Hope it helps someone else too.

 public ActionResult Search(string search = null)  
     {  
       int intSearch;  
       if (!Int32.TryParse(search, out intSearch))  
       {  
       }  
       IEnumerable<Car> cars = context.Cars.Where(  
            c => search == null  
              || c.IntegerField == intSearch  
              || c.Manufacturer.Contains(search)  
              || c.Model.Contains(search)             
             );  
       cars = cars.OrderBy(c => c.Id).ToList();  
       ViewBag.Search = search;  
       return View(cars);  
     }