Skip to content

Instantly share code, notes, and snippets.

@alexeyzimarev
Created December 12, 2014 10:21
Show Gist options
  • Save alexeyzimarev/49da9a79a6e4421cdfb3 to your computer and use it in GitHub Desktop.
Save alexeyzimarev/49da9a79a6e4421cdfb3 to your computer and use it in GitHub Desktop.
Execute stored procedure and get return value, using NHibernate session
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using NHibernate;
namespace NHibernate.Helpers
{
public static class SqlProcedureHelper
{
public static int ExecuteWithReturn(this ISession session, ProcedureQuery query)
{
using (var ts = session.BeginTransaction())
{
var command = new SqlCommand {Connection = (SqlConnection) session.Connection};
ts.Enlist(command);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = query.Procedure;
command.Parameters.AddRange(query.Parameters.ToArray());
var returnParameter = new SqlParameter("@RETURN_VALUE", SqlDbType.Int)
{
Direction = ParameterDirection.ReturnValue
};
command.Parameters.Add(returnParameter);
command.ExecuteNonQuery();
ts.Commit();
return Convert.ToInt32(returnParameter.Value);
}
}
}
public class ProcedureQuery
{
public ProcedureQuery(string procedure)
{
Procedure = procedure;
Parameters = new List<SqlParameter>();
}
public string Procedure { get; private set; }
public List<SqlParameter> Parameters { get; private set; }
public void AddInt32(string name, int value)
{
AddParameter(name, SqlDbType.Int, value);
}
public void AddDecimal(string name, decimal value)
{
AddParameter(name, SqlDbType.Decimal, value);
}
private void AddParameter(string name, SqlDbType type, object value)
{
var parameter = new SqlParameter("@" + name, type)
{
Direction = ParameterDirection.Input,
Value = value
};
Parameters.Add(parameter);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment