view Agendas/trunk/src/Agendas.NHibernate/NhHelper.cs @ 147:5a1f7233aa5a

Agregando algunos tests
author Nelo@Guinea.neluz.int
date Mon, 01 Aug 2011 17:34:35 -0300
parents 2dbb15f4510f
children 5346c0500594
line wrap: on
line source

using AltNetHispano.Agendas.Domain;
using ConfOrm;
using ConfOrm.NH;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Agendas.NHibernate
{
	public static class NhHelper
	{
		private static ISessionFactory _sessionfactory;
		private static Configuration _cfg;

		public static Configuration GetConfiguration()
		{
			if (_cfg == null)
			{
				var orm = new ObjectRelationalMapper();
				orm.TablePerClass<Persona>();
				orm.TablePerClass<Evento>();

				orm.Complex<Evento>(e => e.Estado);

				orm.TablePerClass<Track>();
				orm.TablePerClass<TrackLog>();
				orm.TablePerClass<Cuenta>();
				orm.TablePerClass<Patrocinador>();

				orm.Cascade<Evento, Persona>(Cascade.None);
				orm.Cascade<Persona, Evento>(Cascade.None);

				orm.Cascade<Persona, Cuenta>(Cascade.All | Cascade.DeleteOrphans);

				var mapper = new Mapper(orm);

			    mapper.Customize<Persona>(a => a.Property(p => p.Nombre, m => m.Unique(true)));
                mapper.Customize<Persona>(a => a.Property(p => p.Twitter, m => m.Unique(true)));

                mapper.Customize<Evento>(a => a.Property(p => p.Titulo, m => m.Unique(true)));

				mapper.AddPropertyPattern(p => p.DeclaringType == typeof(Evento) && p.Name == "Estado", a => a.Type<EventoStateType>());

				var mapping = mapper.CompileMappingFor(typeof(Evento).Assembly.GetTypes());
				
				_cfg = new Configuration();
				_cfg.Configure();
				_cfg.AddDeserializedMapping(mapping, null);
			}
			return _cfg;
		}

		public static ISessionFactory GetSessionFactory()
		{
			if (_sessionfactory == null)
			{
				var cfg = GetConfiguration();

#if DEBUG
				var schemaValidator = new SchemaValidator(cfg);
				try
				{
					schemaValidator.Validate();
				}
				catch
				{
					try
					{
						var schemaUpdate = new SchemaUpdate(cfg);
						schemaUpdate.Execute(false, true);

						schemaValidator.Validate();
					}
					catch
					{
						var schemaExport = new SchemaExport(cfg);
						schemaExport.Create(false, true);
					}
				}

#endif

				_sessionfactory = cfg.BuildSessionFactory();
			}
			return _sessionfactory;
		}
	}
}