NHibernate 3.2 : SchemaExport not working with SQLite

标签 nhibernate

我使用内存数据库进行一些快速单元测试,使用以下代码:

public class MemoryDb
{
    private static Configuration configuration;
    private static ISessionFactory sessionFactory;

    static MemoryDb()
    {
        configuration = new NHibernate.Cfg.Configuration();

        configuration.DataBaseIntegration(x =>
        {
            x.Driver<SQLite20Driver>();
            x.Dialect<SQLiteDialect>();
            x.ConnectionProvider<DriverConnectionProvider>();
            x.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            x.IsolationLevel = IsolationLevel.ReadCommitted;
            x.ConnectionString = "Data Source=:memory:;";
            x.Timeout = 255;
            x.BatchSize = 100;
            x.LogFormattedSql = true;
            x.LogSqlInConsole = true;
            x.AutoCommentSql = false;
        });

        configuration.AddMapping(DbHelper.GetAutoMappings());
        sessionFactory = configuration.BuildSessionFactory();
    }

    public static ISession GetSession()
    {
        var session = sessionFactory.OpenSession();
        new SchemaExport(configuration).Execute(true, true, false, session.Connection, null);
        return session;
    }
}

问题是架构导出似乎不起作用。我的测试如下所示:

[Fact]
public void ShouldFindDuplicateByEmail()
{
    using (var session = MemoryDb.GetSession())
    {
        var repo = new NHibernateCustomerRepository(session);
        var customer = new Customer();
        customer.EmailAddress = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d09180e093d09180e09531e1210" rel="noreferrer noopener nofollow">[email protected]</a>";
        repo.Save(customer);

        var duplicates = repo.FindDuplicates(customer);
        Assert.Equal(1, duplicates.Length);
    }
}

测试失败,并出现错误没有这样的表:客户。这一切都适用于 Fluent NHibernate 和 NHibernate 3.1。我知道这不是映射本身的问题,因为当我针对现有的 SQL Server 数据库运行应用程序时,实际的应用程序可以正常工作。仅在运行测试时才会失败。有什么想法吗?

编辑:如果我仅更改连接字符串以使其写入文件(即 x.ConnectionString = "data source="+ Path.GetTempFileName();),则整个过程正常。我猜测要么模式没有针对内存数据库正确运行,要么每次我执行 session 命令时它都会获得一个新的内存数据库,但不知道如何解决这个问题。

最佳答案

我在这里找到了答案:https://forum.hibernate.org/viewtopic.php?p=2397541#p2397541

我必须将以下内容添加到数据库配置中:

x.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;

否则,NHibernate 在刷新每个语句后会释放连接,从而摆脱带有架构的内存数据库。

关于NHibernate 3.2 : SchemaExport not working with SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9853969/

相关文章:

nhibernate - 我可以防止 as HasOne 映射导致数据库调用吗?

c# - NHibernate 在 sql 搜索中使用 .where() 条件还是稍后使用 LINQ?

asp.net-mvc - NHibernate: "failed to lazily initialize...",DDD方法

c# - Linq OrderBy 使用自定义排序顺序

.net - postgresql 中的 NHibernate 映射 citext

.net - NHibernate 支持.NET 4.0 框架吗?

nhibernate - QueryOver by join and add conditions by Independent if

nhibernate - SchemaUpdate 的 future ?

asp.net-mvc - 已经为此应用程序配置了存储机制

Nhibernate Azure 性能