I am using NHibernate with FluentNHibernate for my DAL. I am also using SchemaExport
and SchemaUpdate
to create and update my database schema.
My problem is that the schema operations all require the database to exist before they will work. I want to programmatically create my database and update the schema as there may be multiple databases and the creating of the database is not only a once-off operation.
I know I can do this manually by executing a create database command on a connection to the master database, but this feels wrong considering that I otherwise use NHibernate for all my database interactions. As an aside, I use a SQLite inmemory database for my unit tests so any sql I write will then have to know which database I'm using.
Is there any way to get NHibernate to create my database for me?
NHibernate is Designed to serve as a persistence layer exclusively for the . Net framework based on Object-Relational Mapping Technique. A tool that creates a "virtual representation" of database objects within the code. Used to solve the problem of impedance mismatch between Class and relational databases and tables.
NHibernate is a port of Hibernate from Java, one of the oldest and most respected Object-Relational Mappers (ORMs).
NHibernate is an actively developed, fully featured, open source object-relational mapper for the . NET framework. It is used in thousands of successful projects. It's built on top of ADO.NET and the current version is NHibernate 4.0.
I think that creating db with NHibernate is nice, if you start to develop application with domain model. I mean - it gives an insight how your db should look. But in general - sql scripts should be used.
I heard that some developers uses NHibernate db generation for integration tests, they create lightweight sqlite db on fly.
How to generate db with NHibernate? This is how i do that:
public static void InitSessionFactory()
{
var connectionString =
ConfigurationManager
.ConnectionStrings["MyConnectionString"]
.ConnectionString;
var cfgFromXml = new Configuration();
cfgFromXml.Configure();
var cfg = Fluently.Configure(cfgFromXml)
.Database(MsSqlConfiguration.MsSql2005
.ConnectionString(x => x.Is(connectionString))
.UseReflectionOptimizer())
.Mappings(x => x.FluentMappings
.AddFromAssemblyOf<NHibernateBootstrapper>())
.ExposeConfiguration(BuildSchema);
ObjectFactory.Inject(cfg.BuildSessionFactory());
}
private static void BuildSchema(Configuration config)
{
//Creates database structure
//new SchemaExport(config)
// .Create(false, true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With