Created
January 4, 2011 22:32
-
-
Save felipero/765578 to your computer and use it in GitHub Desktop.
NHibernate Helper ninja fodastico
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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