Skip to content

Instantly share code, notes, and snippets.

@luizdamim
Created June 5, 2013 00:00
Show Gist options
  • Save luizdamim/5710636 to your computer and use it in GitHub Desktop.
Save luizdamim/5710636 to your computer and use it in GitHub Desktop.
Basic `ISessionFactory` setup and class mapping using Loquacious Mappings for NHibernate.
using System.Reflection;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
namespace ManhattanProject
{
public class NHibernateConfig
{
public static ISessionFactory SessionFactory()
{
Configuration cfg = new Configuration();
//cfg.Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>());
cfg.DataBaseIntegration(db =>
{
db.Dialect<NHibernate.Dialect.PostgreSQL82Dialect>();
db.Driver<NHibernate.Driver.NpgsqlDriver>();
db.ConnectionStringName = "Postgres";
db.BatchSize = 200;
db.LogFormattedSql = true;
db.LogSqlInConsole = true;
db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";
});
cfg.SessionFactory().GenerateStatistics();
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
cfg.AddMapping(domainMapping);
return cfg.BuildSessionFactory();
}
}
}
using System;
namespace ManhattanProject.Entities
{
public class User
{
public virtual Guid Id { get; set; }
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual string Email { get; set; }
public virtual DateTime CreatedAt { get; set; }
public virtual string Bio { get; set; }
public virtual Address Address { get; set; }
}
}
using BlogNET.Core.Entities;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
namespace ManhattanProject.Mappings
{
public class UserMap : ClassMapping<User>
{
public UserMap()
{
Schema("public");
Table("users");
Id(p => p.Id, map => map.Generator(Generators.GuidComb));
Property(p => p.Username, map => { map.Length(128); map.NotNullable(true); });
Property(p => p.Password, map => { map.Length(255); map.NotNullable(true); });
Property(p => p.Email, map => { map.Length(255); map.NotNullable(true); });
Property(p => p.CreatedAt, map => { map.Column("created_at"); map.NotNullable(true); map.Generated(PropertyGeneration.Insert); });
Property(p => p.Bio);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment