Skip to content

Instantly share code, notes, and snippets.

@nescalante
Last active December 11, 2015 04:39
Show Gist options
  • Save nescalante/4546973 to your computer and use it in GitHub Desktop.
Save nescalante/4546973 to your computer and use it in GitHub Desktop.
Store Procedure to DataTable Helper
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
public static class DataUtil
{
public static T Fill<T>(string procedureName, string connectionString, object values = null, object mappings = null) where T : DataSet, new()
{
T ds = new T();
// initialize connection
using (var conn = new SqlConnection(connectionString)
{
using (var comm = new SqlCommand(procedureName, conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.AddParameters(values);
var da = new SqlDataAdapter(comm);
conn.Open();
if (mappings == null)
{
da.TableMappings.Add("Table", ds.Tables[0].TableName);
}
else
{
foreach (var pi in mappings.GetType().GetMembers().OfType<PropertyInfo>())
{
var parameter = pi.Name;
var value = pi.GetValue(mappings, null).ToString();
da.TableMappings.Add(parameter, value);
}
}
// fill data set and dispose
da.Fill(ds);
conn.Close();
}
}
return ds;
}
public static SqlCommand AddParameters(this SqlCommand comm, object values)
{
comm.Parameters.Clear();
if (values != null)
{
foreach (var pi in values.GetType().GetMembers().OfType<PropertyInfo>())
{
var parameter = pi.Name;
var value = pi.GetValue(values, null);
SqlDbType type;
if (value is int)
{
type = SqlDbType.Int;
}
else if (value is bool)
{
type = SqlDbType.Bit;
}
else if (value is DateTime)
{
type = SqlDbType.DateTime;
}
else if (value is float)
{
type = SqlDbType.Float;
}
else if (value is byte)
{
type = SqlDbType.TinyInt;
}
else if (value is string)
{
type = SqlDbType.VarChar;
if (value == null)
{
value = System.Data.SqlTypes.SqlString.Null;
}
}
else if (value is int?)
{
type = SqlDbType.Int;
if (value == null)
{
value = System.Data.SqlTypes.SqlInt32.Null;
}
}
else if (value is DateTime?)
{
type = SqlDbType.DateTime;
if (value == null)
{
value = System.Data.SqlTypes.SqlDateTime.Null;
}
}
else if (value is float?)
{
type = SqlDbType.Float;
if (value == null)
{
value = System.Data.SqlTypes.SqlDecimal.Null;
}
}
else if (value is byte?)
{
type = SqlDbType.TinyInt;
if (value == null)
{
value = System.Data.SqlTypes.SqlInt16.Null;
}
}
else
{
throw new InvalidOperationException("type from parameter " + parameter + " not supported.");
}
// add parameter
comm.Parameters.Add("@" + parameter, type).Value = value;
}
}
return comm;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment