使用FluentNhibernate创建数据库后可以对数据库进行种子化?

时间:2017-04-12 20:06:12

标签: c# nhibernate fluent-nhibernate

我希望该数据库在app启动时自动删除并创建(始终删除create database)。创建数据库后,我希望它会自动播种一些测试数据。例如,实体框架有这个机会通过覆盖Seed方法,它如何在Nhibernate中提供更好的?可能在BuildSchema方法中以某种方式做到了吗?

UnitOfWork.cs

public class UnitOfWork : IUnitOfWork
{
    private static readonly ISessionFactory _sessionFactory;
    private ITransaction _transaction;

    public ISession Session { get; private set; }

    static UnitOfWork()
    {
        _sessionFactory = Fluently.Configure()
            .Database(
                MySQLConfiguration.Standard.ConnectionString(
                    x => x.FromConnectionStringWithKey("MarketplaceDevelopment")))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UnitOfWork>())
            .ExposeConfiguration(BuildSchema)
            .BuildSessionFactory();
    }

    private static void BuildSchema(Configuration config)
    {
        new SchemaUpdate(config).Execute(false, true);
    }

    public UnitOfWork()
    {
        Session = _sessionFactory.OpenSession();
    }
    public void BeginTransaction()
    {
        _transaction = Session.BeginTransaction();
    }

    public void Commit()
    {
        try
        {
            // commit transaction if there is one active
            if (_transaction != null && _transaction.IsActive)
            {
                _transaction.Commit();
            }

        }
        catch
        {
            // rollback if there was an exception
            if (_transaction != null && _transaction.IsActive)
            {
                _transaction.Rollback();
            }

            throw;
        }
        finally
        {
            Session.Dispose();
        }
    }

    public void Rollback()
    {
        try
        {
            if (_transaction != null && _transaction.IsActive)
                _transaction.Rollback();
        }
        finally
        {
            Session.Dispose();
        }
    }
}

0 个答案:

没有答案