Search code examples
linqc#-4.0fluent-nhibernatecriterianhibernate-criteria

Build a list of criterias of optional filters for retrieving records nhibernate c#


I have a table with many records in it which can be filtered by rowstatus, created date, modifieddate.

I am using fluent nhibernate as the ORM.

Now the request that can come in the WebAPi can be:

?rowstatus=0 OR ?rowstatus=0&createddate=05-30-2013 OR createddate=05-30-2013 OR modifieddate=05-29-2013&rowsstatus=0

as you can see any combination of filters can come in into the query string.

I wanted to know, how can I dynamically build a list of criteria and give it to my ISession object to execute. what is the best way to do it.

Currently I have so many overloaded functions to do it and it is ugly. Here is an example of what I am using. I want to inject dynamically rowstatus and createddate.

_session.QueryOver<ApiData>()
                           .Where(a => (a.status== rowstatus)
                                       && (a.createdDate== createddate)).List().ToList();

Solution

  • This is how I finally did it:

            var status = queryParams.FirstOrDefault(q => q.Key == "status").Value;
            var entity = queryParams.FirstOrDefault(q => q.Key == "entity").Value;
            var start = queryParams.FirstOrDefault(q => q.Key == "start").Value;
    
            if(!string.IsNullOrEmpty(status))
            {
                query.Where(r => r.RowStatus == Convert.ToInt32(status));
            }
            if (!string.IsNullOrEmpty(entity))
            {
                query.Where(r => r.EntityType == entity);
            }
    
            //Ensure that this should be the last filter criteria to be applied
            if (!string.IsNullOrEmpty(start))
            {
                query.Skip(Convert.ToInt32(start));
            }
    
            var count = query.RowCount();
    
            var results = query.Take(apiUser.ApiLimit).List().Select(c => _cryptography.Decrypt(c.Json)).ToList();