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 23:20 by DanWatson

Comments

October 17. 2009 18:24

trackback

Stored Procedures With Fluent NHibernate

DotNetBurner - burning hot .NET content

DotNetBurner - NHibernate

October 17. 2009 18:34

trackback

Stored Procedures With Fluent NHibernate

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

DotNetKicks.com

December 9. 2009 14: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 23. 2009 16: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 24. 2009 00:24

DanWatson

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

DanWatson

January 8. 2010 19: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 19. 2010 19:45

Vay mua nha

Good post, thank you for sharing useful code

Vay mua nha

January 27. 2010 19:20

Citi Field

thanks for sharing great tutorial Smile

Citi Field

January 27. 2010 19:46

Free Club Penguin

This worked! Great tutorial.

Free Club Penguin

February 5. 2010 07: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 11. 2010 02: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 22. 2010 16: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 9. 2010 01:36

may tinh xach tay

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

may tinh xach tay

March 10. 2010 09: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

March 15. 2010 00:54

conceiving after miscarriage


Nice article, thanks for the information.

conceiving after miscarriage

March 24. 2010 03:25

reverse cell phone lookup

nice post…thanks for sharing

reverse cell phone lookup

March 24. 2010 03:39

reverse phone directory

Do you accept guest posts? I would also like to have copy post here

reverse phone directory

March 24. 2010 03:47

solar panels for your home

great concept for writing...thanks for sharing

solar panels for your home

March 25. 2010 22:38

Diamond Engagement Rings

But before buying your diamond engagement ring you must keep few things in your mind and this article will help you in purchasing a right engagement ring for your lady.

Diamond Engagement Rings

March 27. 2010 03:53

giochi dei casinò in rete

I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful and beneficial to your readers Nice article..

giochi dei casinò in rete

March 29. 2010 12:45

Gratis Online Kasino

This is great…hope i could get one …. i’ve tried to search across the internet..and couldn’t find any of free invite that works..Google’s business model is more complex in some respects and yet also simpler.

Gratis Online Kasino

April 2. 2010 14:09

currency trading tips

Great!By creating a customized Stored ProcedurePart class which implements IMappingPart interface and developer gain some kind of control to merge their Stored Procedure definition into FN mappings.I will keep visiting often for more such information.

currency trading tips

April 2. 2010 14:39

construction games

It is a nice blog!
I am just looking around some pages and I see that it seems to be a pretty attractive platform you are using here. I am currently looking to switch one of these over to a platform just like yours just for a good run. Thanks for your articleSmile

<a href=http://constructiongames.net>construction games</a>

construction games

April 2. 2010 14:41

construction games

It is a nice blog!
I am just looking around some pages and I see that it seems to be a pretty attractive platform you are using here. I am currently looking to switch one of these over to a platform just like yours just for a good run. Thanks for your article;)

construction games

April 3. 2010 15:34

weeds season 5

Great read! thanks

weeds season 5

April 6. 2010 11:49

top picks 2010

Awesome post! Interesting info to know
www.undiscoveredequities.com/top_10_2010.html

top picks 2010

April 7. 2010 00:03

Certified Loose Diamonds

I think, it’s a helpful topic. I like this Stored Procedures With Fluent NH ibernate topic. I want know some helpful things from this side. It fresh my mind and experience. So lots of thanks for sharing this information with me.

Certified Loose Diamonds

April 7. 2010 00:07

Certified Loose Diamonds

I think, it’s a helpful topic. I like this Stored Procedures With Fluent NH ibernate topic. I want know some helpful things from this side. It fresh my mind and experience. So lots of thanks for sharing this information with me.

Certified Loose Diamonds

April 7. 2010 07:31

make money online instantly

I read the article Stored Procedures With Fluent NHibernate and decide this post is competent for this site. This post provide its main option and sharing with all.

make money online instantly

April 9. 2010 23:39

low carb diet

Losing weight healthily you need a healthy diet plans. Low carb diet plans can be an effective way to manage your weight to maintain your desired body in a healthy way.

low carb diet

April 11. 2010 06:05

Dental jobs

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.

Dental jobs

April 11. 2010 06:16

 sonnerie portable

I completely agree with you. I really like this article. It contains a lot of useful information. I can set up my new idea from this post. Thanks so much!

sonnerie portable

April 12. 2010 15:12

gas station canopy manufacturers

hey

Really nice tips!
thanx for some good piece of information

very useful blog!

gas station canopy manufacturers

April 12. 2010 22:20

play online board games

I previously commented onto your web site and picked notify me about latest responses. Can there be a way to eliminate that online system? I am receiving quite a lot of mails.

play online board games

April 13. 2010 10:45

clarisonic review

Thanks for this info on stored procedures, yours was the only site which had this!

clarisonic review

April 13. 2010 21:32

Pizza Banora Point

Although this example only shows a few simple read operation’s even more complex operations are relatively straight forwards to migrate.

Pizza Banora Point

April 13. 2010 21:33

Pizza Banora

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.

Pizza Banora

April 15. 2010 11:34

jouer au blackjack en ligne

I was searching on the web for the same thing, found..but couldn’t figure out how to run..I did have problems with this so plz solve my problem..

jouer au blackjack en ligne

April 16. 2010 19:36

wedding stationery scotland

I think its a great topic. I like it very much. Its so interesting.So i want some information for sharing this side with some of my friend. Thanks.

wedding stationery scotland

April 17. 2010 06:22

Fitness Hoop

I think it is the famous article in all. Every person please visit this site and read this article. It will be provide lot of helpful and interesting things for us.

Fitness Hoop

April 17. 2010 19:01

Go Syco

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?

Go Syco

April 18. 2010 04:58

how to make money online

Stored Procedures With Fluent NHibernate really it is a great  post in all. I got authority for this article in this site. Because i read this post attentively and acquire some useful information.

how to make money online

Comments are closed