简体   繁体   English

使用NHibernate执行DDL语句

[英]Using NHibernate to execute DDL statements

How can I execute a DDL statement via NHibernate? 如何通过NHibernate执行DDL语句?

To be clear, I don't want to auto-generate my schema from my mapping files. 为了清楚起见,我不想从映射文件中自动生成我的模式。 My DDL is stored in plain text files along the lines of: 我的DDL存储在纯文本文件中:

CREATE TABLE Foo (Bar VARCHAR(10))
GO
CREATE TABLE Hello (World INTEGER)
GO

I want to cycle through these in order and execute each of them. 我想按顺序遍历这些并执行它们中的每一个。 I could just open a SqlConnection and execute via a SqlCommand but I'd like to go through NHibernate if there is a nice way to do this. 我可以打开一个SqlConnection并通过SqlCommand执行但我想通过NHibernate,如果有一个很好的方法来做到这一点。 This is mainly because I want to remain as database agnostic as possible: I have a SQL db now but I might need to implement Oracle or DB2 later... 这主要是因为我希望尽可能保持数据库不可知:我现在有一个SQL数据库,但我可能需要稍后实现Oracle或DB2 ...

I'm using .Net v3.51 and NHibernate v2.1. 我正在使用.Net v3.51和NHibernate v2.1。 I looked at the NHibernate SchemaExport class but couldn't see a way to use this for this purpose. 我查看了NHibernate SchemaExport类,但看不到将此用于此目的的方法。

I've used session.Connection.CreateCommand and session.Transaction.EnlistCommand before with success to run raw SQL. 我成功运行原始SQL之前使用了session.Connection.CreateCommandsession.Transaction.EnlistCommand

Here's a snippet of something similar that I've done: 这是我做过的类似事情的片段:

using (var command = _session.Connection.CreateCommand())
{
    _session.Transaction.Enlist(command);
    command.CommandText = "select foo from bar where id = @id";
    var versionIdParameter = command.CreateParameter();
    versionIdParameter.ParameterName = "id";
    versionIdParameter.Value = id;
    command.Parameters.Add(versionIdParameter);
    using(var reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        while (reader.Read())
        // ...
    }
}

You can get an IDbConnection from an ISession's Connection property but you'll need to do this with SqlCommand. 您可以从ISession的Connection属性获取IDbConnection,但是您需要使用SqlCommand执行此操作。 Executing DDL is outside of NHibernate's scope. 执行DDL超出了NHibernate的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM