Skip to content

Instantly share code, notes, and snippets.

@felipero
Created January 4, 2011 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipero/765578 to your computer and use it in GitHub Desktop.
Save felipero/765578 to your computer and use it in GitHub Desktop.
NHibernate Helper ninja fodastico
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using System.Reflection;
namespace Hello_World.Application
{
public class NHibernateHelper
{
private static ISessionFactory sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (sessionFactory == null)
{
// Use in case of your models rest in a differente library: (typeof(Models.Plan).Assembly)
sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey(
"Server=localhost\sqlexpress;Database=plans;User ID=felipe;Password=sdfsdfsdf")))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.BuildSessionFactory();
}
return sessionFactory;
}
}
public static ISession GetCurrentSession()
{
//return session;
if (!CurrentSessionContext.HasBind(SessionFactory))
{
CurrentSessionContext.Bind(SessionFactory.OpenSession());
}
return SessionFactory.GetCurrentSession();
}
public static void DisposeSession()
{
var session = GetCurrentSession();
session.Close();
session.Dispose();
}
public static void BeginTransaction()
{
GetCurrentSession().BeginTransaction();
}
public static void CommitTransaction()
{
var session = GetCurrentSession();
if (session.Transaction.IsActive)
session.Transaction.Commit();
}
public static void RollbackTransaction()
{
var session = GetCurrentSession();
if (session.Transaction.IsActive)
session.Transaction.Rollback();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment