[Update 26th March 2009]: It appears someone has created an easier way of explaining the key elements in getting NHibernate setup and running. You no longer have to navigate your way through this mess of a tutorial
Access it via this link NHibernate in Visual Web Developer Express
[Update 5 August 2008]: You may have noticed that this post is a bit of a rough run through, and not formatted particularly well. I only put this together quickly before I went on a holiday. Since I came back I have been delving into the wonders of ASP.NET 3.5 extensions with LINQ and MVC and haven’t needed to go back to NHibernate. There is however a recent blog on NHibernate you can access here
Tutorial 0.1
This tutorial will show you how to get NHibernate Installed and running using Microsoft Visual Web Developer Express 2005 and Sql Server Express 2005. This is for version 1.20 of NHibernate (2.2?). If you have had endless errors, or just haven’t found a straight forward tutorial, then please follow ALL of these steps. This is by no means the main way you will setup your applications, but it will give you a start, you will see it actually work!.Ok, I have one project that does work, but this second one I setup seems to have difficulty creating the SQL. I haven’t debugged it in NHibenate yet, but I may when I come back form Holidays.
For now, I will assume that you have Web Developer Express and Sql Server Express installed. They are pretty much download and go applications.
- Download and Install NHibernate and NHibernate Extensions
- Create a database called nhibernate in your Sql Server Management Studio Express
- Create a table called User with the following fields
- id, nvarchar(50)
- name,nvarchar(50)
- Create a table called User with the following fields
- Create a new Web Site called NHibernateWeb
- Add a Reference to the NHibernate dll
- Right-click the top item in the Solution Explorer, select Add Reference…
- Click the browse tab
- Find the nhibernate.dll in your install directory/bin/net-2.0/
- You will now have a Bin folder in your Solution Explorer, collapse this.
- Add the following to your Web.config file, just after the <configuration> tag
- ” <configSections>
<section name=”hibernate-configuration”
type=”NHibernate.Cfg.ConfigurationSectionHandler, NHibernate”
/>
</configSections><!– Add this element –>
<hibernate-configuration xmlns=”urn:nhibernate-configuration-2.2″>
<session-factory>
<property name=”dialect”>NHibernate.Dialect.MsSql2000Dialect</property>
<property name=”connection.provider”>NHibernate.Connection.DriverConnectionProvider</property>
<property name=”hibernate.connection.driver_class”>NHibernate.Driver.SqlClientDriver</property>
<property name=”connection.connection_string”>Server=localhost\SQLEXPRESS;initial catalog=nhibernate;Integrated Security=SSPI</property>
<mapping assembly=”App_Code.NHibernateHelpers” />
</session-factory>
</hibernate-configuration> “ - If you don’t have a Web.config file, click the Green Go arrow >, and Web Developer Express will ask if you want to activate debugging, this will create a Web.config for you.
- ” <configSections>
- Right-click your project in Solution Explorer, and click Add New Item
- Select Class File, and call it NHibernateControl.cs
- You will be prompted about putting this into a folder called App_Code…click okay/yes
- Place the following code inside:
- ” using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;namespace NHibernateHelpers
{
public sealed class NHibernateControl
{
private const string CurrentSessionKey = “nhibernate.current_session”;
private static readonly ISessionFactory sessionFactory;static NHibernateControl()
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.Configure();
string basePath = System.Web.HttpContext.Current.Server.MapPath(@”App_Code/”);
cfg.AddXmlFile(basePath + “User.hbm.xml”);
sessionFactory = cfg.BuildSessionFactory();
}public static ISession GetCurrentSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}return currentSession;
}public static void CloseSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;if (currentSession == null)
{
// No current session
return;
}currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}public static void CloseSessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
}
“
- Create a new class under App_Code called User.cs
- And put the following code inside:
- ” using System;
using System.Data;
using System.Configuration;/// <summary>
/// Summary description for Alfie
/// </summary>
namespace NHibernateHelpers
{
public class User
{
private string id;
private string name;public User()
{
//
// TODO: Add constructor logic here
//
}public virtual string Id
{
get { return id; }
set { id = value; }
}public virtual string Name
{
get { return name; }
set { name = value; }
}
}
}
“
- Create a new file under App_Code, but completely rename it to User.hbm.xml
- Put the following in:
- ” <?xml version=”1.0″ encoding=”utf-8″ ?>
<hibernate-mapping xmlns=”urn:nhibernate-mapping-2.2″ namespace=”App_Code.NHibernateHelpers” assembly=”App_Code.NHibernateHelpers”><class name=”App_Code.NHibernateHelpers.User” table=”User”><!– A 32 hex character is our surrogate key. It’s automatically
generated by NHibernate with the UUID pattern. –>
<id name=”Id”>
<column name=”id” length=”40″ not-null=”true” />
<generator class=”uuid.hex” />
</id>
<property name=”Name”>
<column name=”Name” length=”16″ not-null=”true” />
</property>
</class></hibernate-mapping> “
- Create a WebForm, under your main project, called TestNHibernate.aspx. Make sure you select the ‘Place code in seperate file’ option.
- TestNHibernate.cs file, add the following:
- Add the imports: ” using NHibernate;
using NHibernate.Cfg;using NHibernateHelpers;“ - Under the Page_Load function ” ISession session = NHibernateControl.GetCurrentSession();
ITransaction tx = session.BeginTransaction();
User user = new User();
user.Name = “Hello World”;
session.Save(tx);
tx.Commit();
NHibernateControl.CloseSession(); “
- Add the imports: ” using NHibernate;
- TestNHibernate.cs file, add the following:
- Now run the project and you will hopefully see some data in your database!
The User.hbm.xml must be like this:
————————————–
The difference is here:
- default-lazy=”false”
- class name=”NHibernateHelpers.User”
[]´s
Hi I have implemented the example and I am getting this exception..please help me ..thanx in advance.the exception is:-
could not insert: [NHibernateHelpers.User][SQL: INSERT INTO User (Name) VALUES (?); select SCOPE_IDENTITY()]
At the file TestNHibernate.cs
session.Save(tx);
should be
session.Save(user);
Hi,
I have follwed your steps and tried to do the same with VS2008 but when I m running the application .i.e. running TestNHibernate.aspx file, it is giving following error. Please help.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: An error occurred creating the configuration section handler for hibernate-configuration: An exception occurred parsing configuration :The ‘name’ attribute is invalid – The value ‘hibernate.connection.driver_class’ is invalid according to its datatype ‘String’ – The Enumeration constraint failed.
Source Error:
Line 12:
Line 13:
Line 14:
Line 15:
Line 16: NHibernate.Dialect.MsSql2005Dialect
Source File: C:\My\Practice\nHibernateWeb\web.config Line: 14
Hi the above error got fixed as it was due to some type but now I am getting new error. below is the output. Please help asap. I followed the suggestion by essayou but still no luck
Incorrect syntax near the keyword ‘User’.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword ‘User’.
Source Error:
Line 22: user.Name = “Hello World”;
Line 23: session.Save(user);
Line 24: tx.Commit();
Line 25: //session.Update(user);
Line 26: NHibernateControl.CloseSession();
Source File: c:\My\Practice\nHibernateWeb\TestNHibernate.aspx.cs Line: 24
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near the keyword 'User'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +925466
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800118
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +1005
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +149
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135
NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation) +37
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) +569
[GenericADOException: could not insert: [NHibernateHelpers.User][SQL: INSERT INTO User (Name, id) VALUES (?, ?)]]
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) +721
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session) +204
NHibernate.Action.EntityInsertAction.Execute() +75
NHibernate.Engine.ActionQueue.Execute(IExecutable executable) +143
NHibernate.Engine.ActionQueue.ExecuteActions(IList list) +72
NHibernate.Engine.ActionQueue.ExecuteActions() +13
NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) +183
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) +57
NHibernate.Impl.SessionImpl.Flush() +84
NHibernate.Transaction.AdoTransaction.Commit() +168
TestNHibernate.Page_Load(Object sender, EventArgs e) in c:\My\Practice\nHibernateWeb\TestNHibernate.aspx.cs:24
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
folks, Got this also. Need to change the Table name to User1 from User as User is a reserved word in SQL Server
HI Vishrutm,
How did you remove the first error ?
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: An error occurred creating the configuration section handler for hibernate-configuration: An exception occurred parsing configuration :The ‘name’ attribute is invalid – The value ‘hibernate.connection.driver_class’ is invalid according to its datatype ‘String’ – The Enumeration constraint failed.
I am able to remove it ??
Please help ..
HI Vishrutm,
*******************Please reply to this post *******
*****Ignore my prev post **********
I am geeting the first error
How did you remove the first error ?
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: An error occurred creating the configuration section handler for hibernate-configuration: An exception occurred parsing configuration :The ‘name’ attribute is invalid – The value ‘hibernate.connection.driver_class’ is invalid according to its datatype ‘String’ – The Enumeration constraint failed.
I am able to remove it ??
Please help ..