laatzen/LaaProductionWeb/FluentSQL/FluentSQL.cs
2023-06-07 09:19:08 +02:00

117 lines
3.6 KiB
C#

namespace LaaProductionWeb.Data
{
using LaaProductionWeb.Data.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
public class FluentSQL : IFluentSQL
{
private readonly string connectionString;
public FluentSQL(string connectionString)
{
connectionString.ThrowIfNullOrWhiteSpace(nameof(connectionString));
var connectionStringBuilder = new SqlConnectionStringBuilder(connectionString);
this.connectionString = connectionStringBuilder.ToString();
}
public FluentSQLCommand CreateCommand(string commandText)
=> new FluentSQLCommand(this, commandText);
internal int ExecuteNonQuery(FluentSQLCommand command)
{
command.ThrowIfNull(nameof(command));
var rowsAffected = 0;
using (var sqlConnection = new SqlConnection(this.connectionString))
{
sqlConnection.OpenWithErrorHandling();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = command.CommandText;
sqlCommand.Parameters.AddRange(command.Parameters);
rowsAffected = sqlCommand.ExecuteNonQuery();
sqlCommand.Parameters.Clear();
}
}
return rowsAffected;
}
internal IEnumerable<T> ExecuteReader<T>(FluentSQLCommand command, Func<IFluentSQLReader, T> expression)
{
command.ThrowIfNull(nameof(command));
expression.ThrowIfNull(nameof(expression));
using (var sqlConnection = new SqlConnection(this.connectionString))
{
sqlConnection.OpenWithErrorHandling();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = command.CommandText;
sqlCommand.Parameters.AddRange(command.Parameters);
using (FluentSQLReader sqlReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess))
{
sqlCommand.Parameters.Clear();
while (sqlReader.Read())
{
yield return expression(sqlReader);
}
}
}
}
}
internal T ExecuteScalar<T>(FluentSQLCommand command, Func<IFluentSQLReader, T> expression)
{
command.ThrowIfNull(nameof(command));
expression.ThrowIfNull(nameof(expression));
var scalarResult = default(T);
using (var sqlConnection = new SqlConnection(this.connectionString))
{
sqlConnection.OpenWithErrorHandling();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = command.CommandText;
sqlCommand.Parameters.AddRange(command.Parameters);
var scalarObject = sqlCommand.ExecuteScalar();
sqlCommand.Parameters.Clear();
if (scalarObject is T scalarValue)
{
scalarResult = scalarValue;
}
}
}
return scalarResult;
}
internal T FirstOrDefault<T>(FluentSQLCommand command, Func<IFluentSQLReader, T> expression)
=> this
.ExecuteReader(command, expression)
.FirstOrDefault();
}
}