88 lines
2.5 KiB
C#
88 lines
2.5 KiB
C#
namespace Common.Logic.Extensions.SQL
|
|
{
|
|
using Common.Logic.Extensions.SQL.Interfaces;
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data.SqlClient;
|
|
using System.Linq;
|
|
|
|
public class SQLCommand : ISQLCommand
|
|
{
|
|
private readonly SQLConnection sqlConnection;
|
|
private readonly IDictionary<String, SqlParameter> parameters;
|
|
|
|
public SQLCommand(SQLConnection sqlConnection, String commandText)
|
|
{
|
|
this.sqlConnection = sqlConnection.EnsureNotNull(nameof(sqlConnection));
|
|
this.CommandText = commandText.EnsureNotNullOrWhiteSpace(nameof(commandText));
|
|
this.parameters = new Dictionary<String, SqlParameter>();
|
|
}
|
|
|
|
internal String CommandText { get; }
|
|
|
|
internal SqlParameter[] Parameters
|
|
=> this.parameters.Values.ToArray();
|
|
|
|
public Int32 ExecuteNonQuery()
|
|
=> this.sqlConnection.ExecuteNonQuery(this);
|
|
|
|
public IEnumerable<T> ExecuteReader<T>(Func<ISQLReader, T> expression)
|
|
{
|
|
foreach (var result in this.sqlConnection.ExecuteReader(this, expression))
|
|
{
|
|
yield return result;
|
|
}
|
|
}
|
|
|
|
public void ExecuteReader(Action<ISQLReader> expression)
|
|
{
|
|
expression.ThrowIfNull(nameof(expression));
|
|
|
|
this.sqlConnection.ExecuteReader(this, reader =>
|
|
{
|
|
while (reader.Read())
|
|
{
|
|
expression(reader);
|
|
}
|
|
});
|
|
}
|
|
|
|
public T ExecuteScalar<T>(Func<ISQLReader, T> expression)
|
|
=> this.sqlConnection.ExecuteScalar(this, expression);
|
|
|
|
public T FirstOrDefault<T>(Func<ISQLReader, T> expression)
|
|
=> this.sqlConnection.FirstOrDefault(this, expression);
|
|
|
|
public ISQLCommand SetParameter(String name, Object value)
|
|
{
|
|
name.ThrowIfNullOrWhiteSpace(nameof(name));
|
|
|
|
if (value is null)
|
|
{
|
|
value = DBNull.Value;
|
|
}
|
|
|
|
this.parameters[name] = new SqlParameter(name, value);
|
|
|
|
return this;
|
|
}
|
|
|
|
public ISQLCommand SetParameter(String name, DateTime value)
|
|
{
|
|
name.ThrowIfNullOrWhiteSpace(nameof(name));
|
|
|
|
var sqlDate = new DateTime(1753, 1, 1, 12, 0, 0);
|
|
|
|
if (value < sqlDate)
|
|
{
|
|
value = sqlDate;
|
|
}
|
|
|
|
this.parameters[name] = new SqlParameter(name, value);
|
|
|
|
return this;
|
|
}
|
|
}
|
|
}
|