Stored Procedures With Fluent NHibernate

Download The Code

Ok the title of the post may be a little misleading because technically you cannot fluently map stored procedures, but you can still use the NHibernate configuration files to complement your fluent mappings with named query’s (calls on stored procedures).  A while ago I investigated how much work would be involved when making a migration from an ADO.NET to a NHibernate data access implementation whilst slowly swapping out stored procedures to use LINQ 2 NHibernate. Although this example only shows a few simple read operation’s even more complex operations are relatively straight forwards to migrate.

Here is an example of how do fluently map a class as well as map stored procedures.

Below is a method that creates an ISessionFactory  you can see the usual call to create the mappings fluently from the specified assembly, and you can see we can also add Hbm Mappings for the QuestionGroup class.

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using Domain;

namespace Data.Helpers
{
    public class SessionFactory
    {
        public ISessionFactory CreateSessionFactory(string ConnectionString)
        {
            return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005
                              .ConnectionString(
                              C => C.Is(ConnectionString)))
                .Mappings(M => M.FluentMappings.AddFromAssemblyOf<SessionFactory>())
                .Mappings(M => M.HbmMappings.AddClasses(typeof(QuestionGroup)))
                .BuildSessionFactory();
        }       
    }
}

I have a QuestionGroupMap class that takes care of mapping the properties and entities of the QuestionGroup class but I have an additional QuestionGroup.hbm file which defines two stored procedures which then can be called by NHibernate.

using Domain;
using FluentNHibernate.Mapping;

namespace Data.Mappings
{
    public class QuestionGroupMap : ClassMap<QuestionGroup>
    {
        public QuestionGroupMap()
        {
            Id(X => X.QuestionGroupId).GeneratedBy.Identity();
            Map(X => X.QuestionGroupDescription);
            Map(X => X.IsActive);

            HasMany(X => X.Questions).Cascade.All().Inverse().KeyColumnNames.Add("QuestionGroupId");
        }
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <sql-query name="Select_All_Question_Groups">
        <return alias="QuestionGroup" class="Domain.QuestionGroup, Domain">
            <return-property name="QuestionGroupId" column="QuestionGroupId"></return-property>
            <return-property name="QuestionGroupDescription" column="QuestionGroupDescription"></return-property>
            <return-property name="IsActive" column="IsActive"></return-property>
        </return>
        exec Select_All_Question_Groups
    </sql-query>
    <sql-query name="Select_Question_Group">
        <return alias="QuestionGroup" class="Domain.QuestionGroup, Domain"></return>
        exec Select_Question_Group @QuestionGroupId=:QuestionGroupId
    </sql-query>
</hibernate-mapping>

Below shows how the stored procedures are then called in the data access layer (I have added the commented out LINQ 2 NHibernate implementation as well for reference). This is great because as soon as you swap out the stored procedure and use LINQ you get testability for free (see my other post ).

        public IQueryable<QuestionGroup> SelectAll()
        {
            //return from questionGroup in Session.Linq<QuestionGroup>()
            //       select questionGroup;

            return Session
            .GetNamedQuery("Select_All_Question_Groups")
            .List<QuestionGroup>().AsQueryable();
        }

Download The Code (you will need VS2008 Standard / Pro / Team to run this or if your über cool use VS2010 beta).

Twitter Twitter Twitter Twitter Twitter
November 1, 2009 18:20 by DanWatson

Comments

October 25. 2009 06:24

trackback

Stored Procedures With Fluent NHibernate

DotNetBurner - burning hot .NET content

DotNetBurner - NHibernate

October 25. 2009 06:25

trackback

Stored Procedures With Fluent NHibernate

Thank you for submitting this cool story - Trackback from DotNetShoutout

DotNetShoutout

October 25. 2009 06:34

trackback

Stored Procedures With Fluent NHibernate

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com

November 3. 2009 21:32

vitamin c

Stored Procedures are very initial part of every project. By using it we have to do less coding. Thanks for giving this useful coding here. It will be very useful in programming.

vitamin c

November 22. 2009 03:12

Our simply

Thank you for submitting this cool story - Trackback from DotNetShoutout

Our simply

November 27. 2009 03:14

life jackets

Thanks for sharing such nice article on the Stored Procedure. I am beginner in ASP.Net and that article had really helped me in learning the article.

life jackets

December 17. 2009 02:55

organic cotton night shirts womens

Thank you for this cool information! It will be very useful for my project in coming time. Your material is very cognitive and informative. I am going to develop it and then my project will be completely done! Owing to your time my time will be econimized! Thanksss

organic cotton night shirts womens

December 31. 2009 04:28

O Og

Hey the download code link doesn't work. Wasn't sure where the additional hbm file was supposed to go.

O Og

December 31. 2009 12:24

DanWatson

Sorry about that! Have have uploaded the SC for you now.

DanWatson

January 15. 2010 15:49

Wiring Diagram

good info , thanks

Wiring Diagram

January 16. 2010 07:51

payg broadband

NHibernate is otherwise called as Object Relational Mapper (ORM). As the name suggest it bridges the gap and build relationship between object of C# and the world database. NHibernate uses SQL and checks whether the data ends up with correct tables and columns. Your coding helped me to learn a lot. Thanks for sharing.

payg broadband

January 16. 2010 21:03

gambling Java casino games

I went with Identifier Generator and I Configurable
and it worked out well. Still my problem is the forced usage of the legacy database which only accepts the row Id recalculated by the stored procedure dbo.ups_GetNewId which has an Out parameter.

gambling Java casino games

January 20. 2010 03:08

weight loss support

Thanks for sharing...

weight loss support

January 20. 2010 03:12

low carb shakes

Every Tony Ferguson Weight Loss centre have a pharmacist and professionally trained weightloss practitioners on hand to answer any questions. SS

low carb shakes

January 20. 2010 03:13

low carb shakes

Fantastic posted

low carb shakes

January 20. 2010 03:15

weight loss diet

Wow really a great post...

weight loss diet

January 20. 2010 03:16

weight loss plans

Fine dear i like this....

weight loss plans

January 21. 2010 19:58

OzBall Gold Coast

Thanks for the use of the NHibernate configuration files

OzBall Gold Coast

January 27. 2010 07:45

Vay mua nha

Good post, thank you for sharing useful code

Vay mua nha

February 4. 2010 07:20

Citi Field

thanks for sharing great tutorial Smile

Citi Field

February 4. 2010 07:46

Free Club Penguin

This worked! Great tutorial.

Free Club Penguin

February 12. 2010 19:49

phenocal review

I had a great time reading around your post as I read it extensively. I am looking forward to hearing more from you.

phenocal review

February 18. 2010 14:53

trackback

Social comments and analytics for this post

This post was mentioned on Twitter by dotnetguyuk: blogged @dotnetguyuk Stored Procedures With Fluent NHibernate: Download The Code Ok the tit.. http://bit.ly/4dSiqM

uberVU - social comments

February 21. 2010 05:04

canon ink

Very useful info. Hope to see more posts soon!

canon ink

February 22. 2010 03:26

Divaderme Cosmetics

Really its a good news. I am very interested for this post. This side will be help all of us. Thanks.

Divaderme Cosmetics

February 22. 2010 13:22

Income protection insurance

Top post. I look forward to reading more. Cheers ..

Income protection insurance

February 22. 2010 13:23

management consultant

Excellent blog post, I look forward to reading more.

management consultant

February 22. 2010 21:23

dentists

Good post is looking so fine.I like it.Thanks to your post

dentists

February 22. 2010 21:43

SEO

Thanks heaps to the author!
http://www.webmarketingexperts.com.au/

SEO

February 23. 2010 03:54

hardwood floors

Very useful info. Hope to see more posts soon!


hardwood floors

February 24. 2010 06:58

forex vps

complex coding in ASP.Net but you provided comments for the better understanding of it. Thanks. Happy posting!..

forex vps

February 28. 2010 08:43

customer satisfaction service

Its really amazing site.I found many information.Its really helps us.I sharing this site some of my other friend's.I need more information.Please give me.

customer satisfaction service

March 1. 2010 02:35

Terme Di Saturnia

Really its a good news. I am very interested for this post. This side will be help all of us. Thanks.

Terme Di Saturnia

March 1. 2010 19:17

make iphone ringtone

What a nice day.

make iphone ringtone

March 2. 2010 04:41

Phenocal

Fabulous post ,very superb information all the code is very clearly describe .I will bookmark this post , NHibernate is otherwise called as Object Relational Mapper (ORM). As the name suggest it bridges the gap and build relationship between object of C# and the world database. NHibernate uses SQL and checks whether the data ends up with correct tables and columns.
Thanks for sharing.

Phenocal

March 2. 2010 05:44

ucvhost

I am very enjoyed for this side. Its a nice topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. I think it may be help all of you. Thanks.

ucvhost

March 2. 2010 21:29

Youngblood cosmetic

Really its a good news.I found many interesting things from this site. It helps me many away. So many many thanks for sharing this information.

Youngblood cosmetic

March 3. 2010 17:24

Terme Di Saturnia

I think it is a very good post. It helps us many away. So many many thanks for this article.

Terme Di Saturnia

March 7. 2010 18:53

SMO Dubai

Resources like the one you mentioned here is very useful! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

SMO Dubai

March 10. 2010 16:58

Convert PDF to image

Resources like the one you mentioned here will be very useful for me!

Convert PDF to image

March 12. 2010 03:10

Airplane shirts

Thanks for writing about .net NHibernate.. You've got a bunch of really good information here on your website.
Thanks mate.

Airplane shirts

March 13. 2010 00:01

mod converter

I happy to find many good point here,

mod converter

March 13. 2010 00:26

range hood

thank you for the post.
We see more kitchen hoods here.  

range hood

March 16. 2010 13:36

may tinh xach tay

This is really great site, i will come on frequently.

may tinh xach tay

March 17. 2010 13:35

australian employment

Nice job, it’s a great post. The info is good to know!

australian employment

March 17. 2010 13:40

bookkeepers

Awesome post! Interesting info to know.

bookkeepers

March 17. 2010 21:55

Annuity Rates

I must admit that this is one great insight. It surely gives a company the opportunity to get in on the ground floor and really take part in creating something special and tailored to their needs.

Annuity Rates

Add comment



(Will show your Gravatar icon)



 
Are you human? number8 + number7 =