This repository has been archived on 2020-06-09. You can view files and clone it, but cannot push or open issues or pull requests.
dotnet-nhibernate-test/ConsoleApp1/ORM/NHibernateHelper.cs
2020-06-09 00:12:01 +02:00

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();
}
}
}