Click here to Skip to main content
12,999,633 members (45,745 online)
Click here to Skip to main content
Add your own
alternative version


35 bookmarked
Posted 7 Jan 2008

Using Nhibernate in VB.NET

, 7 Jan 2008
Rate this:
Please Sign up or sign in to vote.
Implementation Nhibernate concept in VB.NET


This article is about how to implement Nhibernate in VB.NET.


Refer to to learn what Nhibernate is all about. I use VB 2005 with the backend as PostGres.

Using the Code

It requires Nhibernate.dll files. Download and install Nhibernate files from the above link or search for it in Google.

  1. Create a VB.NET Project - WindowsApplication1
  2. Add a form, place 3 labels and textboxes{eno, ename, salary}, 1 button for save.
  3. Import the following things by adding reference. Right Click in WindowsApplication1. (Don't change the name of the project now).
  4. In the “Add Reference” dialog box, the files to be referred(imported) are:
    • Iesi.Collections.dll
    • log4net.dll
    • Mono.Security.dll
    • Npgsql.dll --- this is for PostGres Users
    • Nhibernate.dll
    • System.Data.Sqlxml
  5. Create a table named testcust in the database. {eno integer, ename varchar2(15), salary integer}. Set Primary key for eno in the table.
  6. Add a class file in the project by “AddNew Item”. Rename or Save it as “testcust.vb”.

    CODING for the Class file is as follows:

    Imports NHibernate
        Imports NHibernate.Cfg
        Imports log4net
        Imports System.Configuration
        Public Class testcust
                Private enumber As Int32
                Private sal As Int32
                Private empname As String
            Public Overridable Property eno() As Int32
                        Return enumber
                End Get
                Set(ByVal value As Int32)
                    enumber = value
                End Set
            End Property
            Public Overridable Property ename() As String
                    Return empname
                End Get
                Set(ByVal value As String)
                    empname = value
                End Set
            End Property
            Public Overridable Property salary() As Int32
                    Return sal
                End Get
                Set(ByVal value As Int32)
                    sal = value
                End Set
            End Property
        End Class
  7. Right click in the WindowsApplication1 -- “Add New Item” -- “Text File”
  8. Rename it as “app.config” and press enter
  9. In the app.config, write the code below:
    (It is here for database connection I used postgresql.)
    <?xml version="1.0" encoding="utf-8" ?>
            <section name="nhibernate"
              type="System.Configuration.NameValueSectionHandler, System, 
             Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"
            <section name="log4net"
              type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"
            <appender name="rollingFile" 
    		type="log4net.Appender.RollingFileAppender, log4net" >
                <param name="File" value="log.txt" />
                <param name="AppendToFile" value="true" />
                <param name="RollingStyle" value="Date" />
                <param name="DatePattern" value="yyyy.MM.dd" />
                <param name="StaticLogFileName" value="true" />
                <layout type="log4net.Layout.PatternLayout, log4net">
                    <param name="ConversionPattern" 
    		value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" />
            <logger name ="MyApp">
                <level value="DEBUG"/>
                <appender-ref ref="rollingFile"/>
                <priority value="DEBUG" />
                <appender-ref ref="rollingFile" />
              value="Server=;Database=GBDEVEL;User Name=erpdotnet;Password=erp"

    If you are using MSSQL 2000, the app.config coding is as below:

    <?xml version="1.0" encoding="utf-8" ?>
    	   Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
    		initial catalog=nhibernate;Integrated Security=SSPI"

    Note: Change the user name, password, server name as suitable to you.

  10. In the Form1, add 3 labels and textboxes to enter eno, ename, salary and a button to save. The coding is as follows:
    Imports NHibernate
    Imports NHibernate.Cfg
    Imports log4net
    Imports System.Configuration
    Imports NHibernate.Connection
    Imports Iesi.Collections
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, _
    	ByVal e As System.EventArgs) Handles Button1.Click
            Dim myConfig As New Configuration
            myConfig.SetProperty("hibernate.dialect", _
            'Dim myFactory As ISessionFactory = myConfig.Configure.BuildSessionFactory
            Dim myFactory As ISessionFactory = myConfig.BuildSessionFactory
            Dim mySession As ISession = myFactory.OpenSession
            Dim myTransaction As ITransaction = mySession.BeginTransaction
            Dim cust As New testcust
            cust.eno = TextBox1.Text
            cust.ename = TextBox2.Text
            cust.salary = TextBox3.Text
        End Sub
    End Class
  11. Likewise as the class file, open a text file and rename it as “testcust.hbm.xml”. The coding for this is:
    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
        <class name="WindowsApplication1.testcust, 
    	WindowsApplication1" table="erp.testcust">
            <id name="eno" column="eno" type="Int32">
                <generator class="assigned" />
            <property name="ename" column="ename" type="String" length="15" />
            <property name="salary" column="salary" type="Int32" length="12" />

    Note: Make sure with the data type used in the table in database, class file and the property name here used are case-sensitive. For example: salary defined in class file or database must have the same name here. Salary is itself wrong. You may get ADOException Unhandled or Column Mismatch Exception. Mention the database table name correctly, if you used it with schema. The <generator class = “assigned”> or <generator class = “identity”> can be used. Both may have different effects based on the constraints you set to the attributes.

  12. Make sure that “testcust.hbm.xml” file's property of Build Action is selected as Embedded Resources (default is none or compile). You may get Mapping Exception of entity or class due to this, if not selected.
  13. Save this VB.NET Project properly and Run it.
  14. You can also use “hibernate.cfg.xml” instead of “app.config”. The coding for that is:
    <?xml version='1.0' encoding='utf-8'?>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
        <!-- an ISessionFactory instance -->
            <!-- properties -->
            <property name="connection.provider">
            <property name="connection.driver_class">
            <property name="connection.connection_string">
    		Server=;Database=GBDEVEL;User Name=erpdotnet;
            <property name="show_sql">false</property>
            <property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
            <property name="use_outer_join">true</property>
            <!-- mapping files -->
            <mapping resource="WindowsApplication1.testcust.hbm.xml" 
    		assembly="WindowsApplication1" />

    Note: If you are using app.config, don't write hibernate.cfg.xml. If you are using this, don't use app.config.

  15. For MSSQL2000, use this for the property tag:
      <property name="connection.provider">
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver
    <property name="connection.connection_string">
    	Server=(local);initial catalog=AdventureWorks;User Id=sa;
    <property name="show_sql">false</property>
    <property name="dialect"> NHibernate.Dialect.MsSql2000Dialect </property>
    <property name="use_outer_join">true</property>

    Note: Change the username, password, server name as suitable for you.

  16. Make sure you import and connect everything properly and change the properties of BuildAction -- Embedded Resources of “testcust.hbm.xml”. You may get ADO EXCEPTIONS, if not!!!!!
  17. Enjoy the coding.

You can also use VB.NET 2005.

Points of Interest

Learn how some exceptions occur and why and how to solve that.


  • 7th January, 2008: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
VitorHugoGarcia10-May-13 4:41
memberVitorHugoGarcia10-May-13 4:41 
QuestionError while execute query Pin
Aarti Meswania4-Mar-13 22:10
memberAarti Meswania4-Mar-13 22:10 
I have another problem

below code is not working Frown | :(
Setting obj = (Setting)session.CreateQuery("from tbl s where s.Id=:first").SetParameter("first", 1).UniqueResult();

ERROR is,...
key=value argument incorrect in ConnectionString\r\nParameter name: data source

please help
General5+ Pin
Aarti Meswania4-Mar-13 22:08
memberAarti Meswania4-Mar-13 22:08 
GeneralMy vote of 5 Pin
nikhi _singh8-Feb-12 18:20
membernikhi _singh8-Feb-12 18:20 
GeneralNHibernate-2.0.0 Beta1 and VB.Net in VS.Net2005 using MSSQL2005 Pin
MrBaseball348-Jul-08 10:10
memberMrBaseball348-Jul-08 10:10 
GeneralSimple and good. Pin
dnpro30-May-08 1:27
memberdnpro30-May-08 1:27 
GeneralConfiguration section Pin
FabioMaulo8-Jan-08 22:22
memberFabioMaulo8-Jan-08 22:22 
GeneralRe: Configuration section Pin
reloded3-May-12 7:33
memberreloded3-May-12 7:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170624.1 | Last Updated 8 Jan 2008
Article Copyright 2008 by S.SRIVATHSAN
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid