Using NHibernate to execute DDL statements

谁说我不能喝 提交于 2020-01-03 20:57:10

问题


How can I execute a DDL statement via NHibernate?

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:

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. 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...

I'm using .Net v3.51 and NHibernate v2.1. I looked at the NHibernate SchemaExport class but couldn't see a way to use this for this purpose.


回答1:


You can get an IDbConnection from an ISession's Connection property but you'll need to do this with SqlCommand. Executing DDL is outside of NHibernate's scope.




回答2:


I've used session.Connection.CreateCommand and session.Transaction.EnlistCommand before with success to run raw SQL.

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())
        // ...
    }
}


来源:https://stackoverflow.com/questions/2023120/using-nhibernate-to-execute-ddl-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!