After a couple of months off Mapping By code, I have been using it again for a small project that I am working on. I found my previous blog posts a useful reminder, but realised that I hadn’t added any sample code for building a session factory.
So here is is, a sample Session factory builder using NH 3.3 and Mapping by Code:
public class SessionFactoryBuilder
{
public static ISessionFactory BuildSessionFactory()
{
var nhConfiguration = ConfigureNHibernate();
var mapping = GetMappings();
nhConfiguration.AddDeserializedMapping(mapping, "PUT MAPPING NAME HERE");
return nhConfiguration.BuildSessionFactory();
}
private static Configuration ConfigureNHibernate()
{
var configure = new Configuration();
configure.SessionFactoryName("BuildIt");
configure.DataBaseIntegration(db =>
{
db.Dialect<MsSql2008Dialect>();
db.Driver<SqlClientDriver>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.IsolationLevel = IsolationLevel.ReadCommitted;
db.ConnectionString = ConfigurationManager.ConnectionStrings["CONNECTION_STRING_KEY"].ConnectionString;
db.Timeout = 10;
// enabled for testing
//db.LogFormatedSql = true;
db.LogSqlInConsole = true;
//db.AutoCommentSql = true;
});
return configure;
}
protected static HbmMapping GetMappings()
{
//There is a dynamic way to do this, but for simplicity I chose to hard code
var mapper = new ModelMapper();
mapper.AddMapping<PersonMap>();
var mapping = mapper.CompileMappingFor(new[] { typeof(Person) });
return mapping;
}
}
Inferred Mappings
If you simply want to point the ModelMapper at an assembly and let it work out which mapping classes to include, you can use the following syntax:
mapper.AddMappings(Assembly.GetAssembly(typeof(AssetIdentifierMap)).GetExportedTypes());
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
Conventions
I tend to tread lightly with conventions, but here are a couple that I use regularly:
class – Id Convention
Map the Id property of the class to a column with the name ClassType + “Id” and use an Identity Generator for new id vals.
mapper.BeforeMapClass += (mi, t, map) => map.Id(
x =>
{
x.Column(t.Name + "Id");
x.Generator(Generators.Identity);
});
In the above a class Person with a Id property would have the Id property mapped to a column called “PersonId”.
Many To One Convention
Maps many to one properties (i.e. foreign key columns) to a column with the name “RelatedClassType” + Id
mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) =>
map.Column(propertyPath.LocalMember.GetPropertyOrFieldType().Name + "Id");