Search code examples
c#nhibernateasp.net-mvc-5queryover

Having a search function that returns all values that contain the searchstring


I'm trying to get a search function on my page that searches my entire database in the column 'Value' for all results that contain the search string. I'm using NHibernate for my project and I'm still getting used to the way queries should be specified.

My current search function:

[HttpGet]
public ActionResult Search(string searchString)
{
    var searchResult = DbSession.QueryOver<Translation>()                                                         
                                .Where(x => x.Value.Contains(searchString))
                                .List(); 
    return Json(searchResult, JsonRequestBehavior.AllowGet);
}

The eventual query will have some more restrictions, but at first I need to filter the data so that the list only contains the values that contain searchString. I'm getting a System.Exception on the .Where(x => x.Value.Contains(searchString)) part at the moment. Anyone has any ideas?

Thanks in advance!


Solution

  • The QueryOver is different from linq, so you must use the WhereRestrictionOn method. Or use the Where with a criteria. Below is an example using WhereRestrictionOn:

    [HttpGet]
    public ActionResult Search(string searchString)
    {
        var searchResult = DbSession.QueryOver<Translation>()
                                .WhereRestrictionOn(x => x.Value).IsLike("%" + searchString + "%")
                                .List(); 
        return Json(searchResult, JsonRequestBehavior.AllowGet);
    }
    

    See more here: http://nhibernate.info/blog/2009/12/17/queryover-in-nh-3-0.html