3
votes

I`m using PostgreSQL and Fluent NHibernate with code first entities and mappings in ASP.NET MVC4 Application.

When i run application it automatically deletes every record from database.

This is my NHibernateHelper Class

public class NHibernateHelper
{
    private static ISessionFactory _sessionFactory;

    private static ISessionFactory SessionFactory 
    {
        get 
        {
            if (_sessionFactory == null)
                InitializeSessionFactory();
            return _sessionFactory;
        }
    }

    private static void InitializeSessionFactory()
    {
        _sessionFactory = Fluently.Configure()
            .Database(PostgreSQLConfiguration.Standard
                        .ConnectionString(
                            @"Server=localhost;Port=5432;Database=TestDB;User=postgres;Password=postgre;")
                        .ShowSql()
            )
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProductCategory>())
            .ExposeConfiguration(cfg => new SchemaExport(cfg)
                            .Create(true, true))
            .BuildSessionFactory();
    }

    public static ISession OpenSession() 
    {
        return SessionFactory.OpenSession();
    }

Is there any incorrect configuration?

1

1 Answers

8
votes

I'd say that the problem lies here:

.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true,true))

It seems you're exporting the schema every time when building the session factory. Now I'm not 100% sure (I have never used code-first to generate the tables, only mapped to the existing database I created beforehand), but I bet that the export overwrites what you already have (drop & recreate or whatever).

Here someone had a similar problem with SQLite file getting overwritten when exporting schema with Fluent NHibernate, so I'd say you have to be careful when and how you (re)create the database :)