48 lines
1.6 KiB
C#
48 lines
1.6 KiB
C#
using System.Collections.Generic;
|
|
using ConsoleApp1.Model;
|
|
using NHibernate;
|
|
using NHibernate.Cfg;
|
|
using NHibernate.Cfg.MappingSchema;
|
|
using NHibernate.Mapping.ByCode;
|
|
|
|
namespace ConsoleApp1.ORM
|
|
{
|
|
public static class NHibernateHelper
|
|
{
|
|
private static ISessionFactory _sessionFactory;
|
|
private static Configuration _configuration;
|
|
private static HbmMapping _mapping;
|
|
|
|
public static ISession OpenSession()
|
|
{
|
|
//Open and return the nhibernate session
|
|
return SessionFactory.OpenSession();
|
|
}
|
|
|
|
public static ISessionFactory SessionFactory => _sessionFactory ??= Configuration.BuildSessionFactory();
|
|
|
|
public static Configuration Configuration => _configuration ??= CreateConfiguration();
|
|
|
|
public static HbmMapping Mapping => _mapping ??= CreateMapping();
|
|
|
|
private static Configuration CreateConfiguration()
|
|
{
|
|
var configuration = new Configuration();
|
|
//Loads properties from hibernate.cfg.xml
|
|
configuration.Configure();
|
|
//Loads nhibernate mappings
|
|
configuration.AddDeserializedMapping(Mapping, null);
|
|
|
|
return configuration;
|
|
}
|
|
|
|
private static HbmMapping CreateMapping()
|
|
{
|
|
var mapper = new ModelMapper();
|
|
//Add the person mapping to the model mapper
|
|
mapper.AddMappings(new List<System.Type> { typeof(PersonMap) });
|
|
//Create and return a HbmMapping of the model mapping in code
|
|
return mapper.CompileMappingForAllExplicitlyAddedEntities();
|
|
}
|
|
}
|
|
} |