Smart InputModels with NHibernate in C#

2014-02-21

I’ve been using Nhibernate for a while now and found a way to handle queryfiltering when the user needs to have a lot of filter possabilities. That is a big form with a lot of inputs for the user to fill in.

The controlleraction

The controller action might look something like this:

 

The InputModel

As you can see in the gist above its acctually the inputmodel that’s in charge of the condition applying and not the controller itselves. This is done with the magic of Expressions and Funcs in c#. Here it is:

 

In the example above you can see a property being set in the contructor. What this actually means is that when a user is running the action in the controller the modelbinder will create an instance of the inputmodel and the constructor will act as the default values of the filter form. When the user is filling in the form from the view the modelbinder vill override thies values wich we want.

 

Extenssion

Since NHibernate dont actually have a Where method on thier IQueryOver interface wich supports a IEnumerable of conditions we need to create a extenssion method for it. But that is simple enought. It could look something like this:

 

JoinQueryOver

The nice thing with this architecture is that we can expand the inputmodel to handle filtering of fetched objects aswell. I could look something like this:

 

I dont think i need to show you have the inputmodel ”PackageConditions()” method will look like since it will basicly look like the ”Conditions()” method but with the packagetype as Func generic (Func).

 

Maybe in a later blogpost i can tell you guys how you can use this method of filtering with a paged list, where we dont load all rows from the database.

I wrote this!

The name is Dennis Sangmo!

Jag har ett brinnande intresse av att utveckla webbapplikationer och gör detta både professionellt och på min fritid. En stor del av den tiden jag inte spenderar till att utveckla brukar jag lägga på att läsa på och hålla mig uppdaterad i utvecklings-sfären på internet.

Under det senaste året har jag ökat mitt intresse för att designa användarvänliga applikationer och allt som hör till att öka den positiva upplevelsen hos en besökare eller användare.