NHibernate,SQLite和ATTACH DATABASE

时间:2010-12-29 10:03:41

标签: sqlite nhibernate

我正在尝试做一些不寻常的事情......我目前有一个SQLite数据库,可以通过NHibernate访问。该数据库经常上传到服务器。我有一个新的要求是为报告目的创建一个新表,预计会变得非常大。这个表不需要上传到服务器,所以我想将它放在一个单独的数据库中,并使用ATTACH DATABASE从我的主数据库透明地访问它。

问题是我不知道如何使用NHibernate ...如何在连接时告诉NHibernate附加其他数据库?我找不到任何连接字符串参数或NH配置属性允许这样做......它甚至可能吗?

可接受的选项是在连接打开时手动执行ATTACH DATABASE命令,但我不知道该怎么做。当我构建NH会话工厂时,它会立即尝试更新架构(hbm2ddl.auto = update),并且在此之前我没有机会对连接做任何事情。所以它只会尝试在我的主数据库上创建新表,这当然不是我想要的......

以前有人曾经这样做过吗?你是怎么做到的?

由于


编辑:如果有人需要这样做,这是我的解决方案,灵感来自迭戈的答案

连接提供商:

public class AttachedDbConnectionProvider : DriverConnectionProvider
{
    private string _attachedDbAlias;
    private string _attachedDbFileName;

    public override IDbConnection GetConnection()
    {
        var connection = base.GetConnection();
        if (!string.IsNullOrEmpty(_attachedDbAlias) && !string.IsNullOrEmpty(_attachedDbFileName))
        {
            using (var attachCommand = connection.CreateCommand())
            {
                attachCommand.CommandText = string.Format(
                    "ATTACH DATABASE '{0}' AS {1}",
                    _attachedDbFileName.Replace("'", "''"),
                    _attachedDbAlias);
                attachCommand.ExecuteNonQuery();
            }
        }
        return connection;
    }

    public override void Configure(IDictionary<string, string> settings)
    {
        base.Configure(settings);
        settings.TryGetValue("connection.attached_db_alias", out _attachedDbAlias);
        settings.TryGetValue("connection.attached_db_filename", out _attachedDbFileName);
    }
}

配置文件:

<property name="connection.provider">MyApp.DataAccess.AttachedDbConnectionProvider, MyApp.DataAccess</property>
<property name="connection.attached_db_alias">reportdb</property>
<property name="connection.attached_db_filename">mydatabase.report.db</property>

现在,要将类映射到附加数据库中的表,我只需要指定“reportdb”。在映射文件中

1 个答案:

答案 0 :(得分:1)

这可能会有所帮助......

public class MyConnectionProvider : DriverConnectionProvider
{
    public override IDbConnection GetConnection()
    {
        var connection = base.GetConnection();
        var attachCommand = connection.CreateCommand();
        attachCommand.CommandText = "ATTACH DATABASE FOO";
        attachCommand.ExecuteNonQuery();
        return connection;
    }
}

配置:

<property name="connection.provider">MyConnectionProvider, MyAssembly</property>
相关问题