Skip to content

Instantly share code, notes, and snippets.

@Reizinixc
Created June 18, 2017 12:01
Show Gist options
  • Save Reizinixc/31c007c1acb24830bd5d16a0498c8dd9 to your computer and use it in GitHub Desktop.
Save Reizinixc/31c007c1acb24830bd5d16a0498c8dd9 to your computer and use it in GitHub Desktop.
IDbCommand extension methods
using System;
using System.Data;
using System.Data.Common;
namespace Reizinixc.Common.Database.Extensions
{
/// <summary>
/// Represents an extension class provides methods to be more convenient to work with
/// <see cref="IDbCommand" />.
/// </summary>
public static class DbCommandExtensions
{
/// <summary>
/// Adds a command's parameter to the current <see cref="IDbCommand" /> with parameter name,
/// value and <see cref="DbType" /> that matched the value.
/// </summary>
/// <param name="command">The command to be added a parameter.</param>
/// <param name="name">The parameter name to be added.</param>
/// <param name="value">The parameter value associated with a specified parameter name.</param>
/// <param name="type">The type of a specified parameter value.</param>
/// <returns>The <see cref="IDbCommand" /> with provided parameter.</returns>
public static IDbCommand AddParameter(this IDbCommand command, string name, object value, DbType type)
{
if (command == null)
{
throw new ArgumentNullException(nameof(command));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var parameter = command.CreateParameter();
parameter.ParameterName = name;
parameter.Value = value;
parameter.DbType = type;
command.Parameters.Add(parameter);
return command;
}
/// <summary>
/// Sets a parameter value which already provided to the current <see cref="IDbCommand" />
/// to a new specified value and type.
/// </summary>
/// <param name="command">The command to be set a specified parameter.</param>
/// <param name="name">The parameter name associated with a value to be set.</param>
/// <param name="value">The parameter value to be set.</param>
/// <returns>The <see cref="IDbCommand" /> with a provided parameter.</returns>
public static IDbCommand SetParameter(this IDbCommand command, string name, object value)
{
if (command == null)
{
throw new ArgumentNullException(nameof(command));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
// Because an implementation of IDbCommand instance contains a parameter as a
// DbParameter-implemented instance and returns as IDataParameterCollection which
// cannot access to parameter value. We have to cast down to DbParameter in order to
// be able to set the parameter from a value returns from index accessing.
if (command.Parameters[name] is DbParameter parameter)
{
parameter.Value = value;
}
return command;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment