Kash Farooq's software development blog

.NET Developer

Creating a database schema with Fluent NHibernate

Posted by Kash Farooq on July 17, 2012

If you create your model in C# first, and then want to create a database schema that matches that model, you can do this easily with Fluent NHibernate.

First, you need some sort of Data Access Initialization class.

public class DataAccessInitializer
{
  private static ISessionFactory sessionFactory;
  private readonly FluentConfiguration fluentConfiguration;
  private Configuration nhibernateConfiguration;

  public DataAccessInitializer()
  {
    //Fluently configure nHibernate and save the nHibernate config that has been created by Fluent
    fluentConfiguration = CreateFluentConfiguration().ExposeConfiguration(cfg => nhibernateConfiguration = cfg);
  }

  public Configuration NhibernateConfiguration
  {
    get { return nhibernateConfiguration; }
  }

  public ISessionFactory CreateSessionFactory()
  {
    return sessionFactory ?? (sessionFactory = fluentConfiguration.BuildSessionFactory());
  }

  private static FluentConfiguration CreateFluentConfiguration()
  {
    var entitiesToMapConfiguration = new EntitiesToMapConfiguration();
    return Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2008
                        .ConnectionString(x => x.Server(".")
                        .Database("nHibernateAndWebSessionManagement")
                        .TrustedConnection()))
        .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Movie>(entitiesToMapConfiguration))); //Movie is one of my entities that needs mapping
  }

  //Class to limit the objects Fluent is interested in
  private class EntitiesToMapConfiguration : DefaultAutomappingConfiguration
  {
    public override bool ShouldMap(Type type)
    {
      return type.Namespace == "MovieSearch.DataAccess.Entities"; //only use classes in this namespace.
    }
  }
}

You could use this to create your Session Factory for any app. Note that I’ve created a EntitiesToMapConfiguration class to limit the types that Fluent is interested in. I don’t want NHibernate to start looking for a DataAccessInitializer table.

I’ve done one extra thing that you don’t need if you just want to create sessions from the Session Factory: I’ve called FluentConfiguration.ExposeConfiguration to save the NhibernateConfiguration into a private variable. I have also created a public NhibernateConfiguration property that exposes this so that it can specifically be used by the following code to create the database schema:


[TestFixture]
public class DataAccessTest
{
  private static void BuildSchema(Configuration cfg)
  {
    new SchemaUpdate(cfg).Execute(true, true);
  }

  [Test]
  [Explicit]
  public void CreateSchema()
  {
    var dataAccessService = new DataAccessInitializer();
    dataAccessService.CreateSessionFactory();
    BuildSchema(dataAccessService.NhibernateConfiguration);
  }
}

I’ve wrapped the runner in an NUnit test, and used the ExplicitAttribute to prevent the test from running accidentally – it won’t run if you chose to run all tests in a solution, only if you run that one test explicitly.

Advertisements

Sorry, the comment form is closed at this time.

 
%d bloggers like this: