This is the third and last part of a series of articles about using NHibernate in an ASP.NET MVC application. These are the links of the two previous posts:
In this article we will create our ASP.NET MVC application to manage Posts and Categories. Our project will have the following structure:
The CategoriesController will let us Fetch, Create,Update and delete categories from our repository.
The PostController will let us do the equivalent for Posts, for the Post views I’m using a ViewModel to represent the combination of Posts and Categories.
In our ASP.NET MVC applications we will add references to our Core and Infrastructure projects in order to use our NHibernate persistency components.
We are using strongly-typed views based on our Models an ViewModel so the tool can scaffold our views based on those types.
I did little changes to the code (thanks to Unit Testing I detected some bugs in the code), so make sure to download the complete version of the project.
ViewModel
The Posts views needs the Post and Category domain objects to render properly, a common pattern is to introduce a view model that acts as a container for those objects in order to facilitate the render of the View.
For the Posts controller views, I’m not directly using the Domain Model (Post and Category classes), instead I created a PostViewModel that contains those domain objects. This way I can simplify handling Posts and related Categories as a “single unit”.
Conclusion
Configuring NHibernate the first time may require a some effort (a little bit), but it will save you a lot of time while working in the data layer of your application, combined with a framework like ASP.NET MVC you can have a clear separation of concerns that enables you keep your project well organized, easy to understand and create unit tests. I believe the result of this process is an elegant project structure and code and Visual Studio templates for ASP.NET MVC make the job even easier since you can scaffold the Views.
It’s amazing how easy and fast is to create applications with ASP.NET MVC, I’m looking forward for version 2.0 (I’m already playing with the Preview version). It’s an exciting time to learn ASP.NET, MVC and NHibernate.
Posted by ASP.NET MVC and NUnit « Forerunner-G34 on November 7, 2009 at 2:49 am
[...] About « Using ASP.NET MVC and NHibernate (Part 3 – final) [...]