Skip to content

Instantly share code, notes, and snippets.

@juanonsoftware
Created July 3, 2015 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanonsoftware/f4b3e85415ccdcab2161 to your computer and use it in GitHub Desktop.
Save juanonsoftware/f4b3e85415ccdcab2161 to your computer and use it in GitHub Desktop.
NHiberate - Code to make SchemaExport generate database for entities mapping class
using System;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using NHibernate.Tool.hbm2ddl;
namespace ConsoleApplication1
{
public class Item
{
public int Id { get; set; }
public string Description { get; set; }
}
public class ItemMap : ClassMapping<Item>
{
public ItemMap()
{
Id(e => e.Id, m => m.Generator(Generators.Identity));
Property(e => e.Description, m =>
{
m.NotNullable(true);
m.Length(10000);
});
}
}
class Program
{
private const string ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=db01;Integrated Security=True";
static void Main(string[] args)
{
var modelMapper = BuildModelMapper();
var configuration = GetConfiguration();
configuration.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), null);
try
{
new SchemaExport(configuration).Execute(false, true, false);
Console.WriteLine("Done");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
private static ModelMapper BuildModelMapper()
{
var mm = new ModelMapper();
mm.AddMapping(typeof(ItemMap));
return mm;
}
private static Configuration GetConfiguration()
{
var cfg = new Configuration();
cfg.DataBaseIntegration(db =>
{
db.Driver<SqlClientDriver>();
db.Dialect<MsSql2008Dialect>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.ConnectionString = ConnectionString;
db.LogFormattedSql = true;
db.LogSqlInConsole = true;
db.AutoCommentSql = true;
});
return cfg;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment