Raw SQL Queries with NHibernate

Saturday, October 17th, 2009 at 4:49 pm

If you want to execute a native SQL query and don’t care about the result, just grab the ADO.NET database connection from the NHibernate session and use that to run the query.

Here’s the code:

// Get the NHibernate Session (this line will change depending how you do it)
NHibernate.ISession session = SessionManager.GetInstance();
// Create a SQL Command
System.Data.IDbCommand command = session.Connection.CreateCommand();
// Set the query you're going to run
command.CommandText = "INSERT INTO Users ('Peter', 'Piper')";
// Run the query
command.ExecuteNonQuery();

Leave a Reply