64 lines
1.9 KiB
C#
64 lines
1.9 KiB
C#
namespace LaaProduction.SQL
|
|
{
|
|
using System;
|
|
using System.Data.SqlClient;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
public static class SQLExtensions
|
|
{
|
|
internal static T EnsureNotNull<T>(this T value, [CallerMemberName] string memberName = "")
|
|
{
|
|
value.ThrowIfNull(memberName);
|
|
|
|
return value;
|
|
}
|
|
|
|
internal static string EnsureNotNullOrWhiteSpace(this string value, [CallerMemberName] string memberName = "")
|
|
{
|
|
value.ThrowIfNullOrWhiteSpace(memberName);
|
|
|
|
return value;
|
|
}
|
|
|
|
internal static void ThrowIfNull<T>(this T value, [CallerMemberName] string memberName = "")
|
|
{
|
|
if (value == null)
|
|
{
|
|
throw new ArgumentException($"{memberName} should not be null.", memberName);
|
|
}
|
|
}
|
|
|
|
internal static void ThrowIfNullOrWhiteSpace(this string value, [CallerMemberName] string memberName = "")
|
|
{
|
|
if (string.IsNullOrWhiteSpace(value))
|
|
{
|
|
throw new ArgumentException($"{memberName} should not be null or white space.", memberName);
|
|
}
|
|
}
|
|
|
|
internal static void OpenWithErrorHandling(this SqlConnection sqlConnection, Action<string> errorCallback)
|
|
{
|
|
sqlConnection.ThrowIfNull(nameof(sqlConnection));
|
|
|
|
sqlConnection.FireInfoMessageEventOnUserErrors = true;
|
|
|
|
if (errorCallback != null)
|
|
{
|
|
sqlConnection.InfoMessage += (_, args) => errorCallback(args.Message);
|
|
}
|
|
|
|
sqlConnection.Open();
|
|
}
|
|
|
|
public static object SqlValue(this object value, int index)
|
|
{
|
|
if (value is null)
|
|
{
|
|
return DBNull.Value;
|
|
}
|
|
|
|
return $"'{new SqlParameter($"x{index}", value).SqlValue}'";
|
|
}
|
|
}
|
|
}
|