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

151 lines
3.5 KiB
C#

namespace LaaProductionWeb.Data
{
using LaaProductionWeb.Data.Interfaces;
using System;
using System.Data.SqlClient;
public class FluentSQLReader : IFluentSQLReader, IDisposable
{
private readonly SqlDataReader sqlDataReader;
private int index;
private FluentSQLReader(SqlDataReader sqlDataReader)
=> this.sqlDataReader = sqlDataReader.EnsureNotNull(nameof(sqlDataReader));
public void Dispose()
{
this.sqlDataReader.Close();
this.sqlDataReader.Dispose();
}
public bool GetBool()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
return this.sqlDataReader.GetBoolean(this.index);
}
return default(bool);
}
public byte[] GetBytes()
{
this.index++;
var bytes = default(byte[]);
if (!this.sqlDataReader.IsDBNull(this.index))
{
bytes = this.sqlDataReader.GetFieldValue<byte[]>(0);
}
return bytes ?? Array.Empty<byte>();
}
public DateTime GetDate()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
return this.sqlDataReader.GetDateTime(this.index);
}
return default(DateTime);
}
public int GetInt()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
return this.sqlDataReader.GetInt32(this.index);
}
return default(int);
}
public long GetLong()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
return this.sqlDataReader.GetInt64(this.index);
}
return default(long);
}
public short GetSmallint()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
return this.sqlDataReader.GetInt16(this.index);
}
return default(short);
}
public string GetString()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
return $"{this.sqlDataReader.GetValue(this.index)}";
}
return default(string);
}
public T GetValue<T>()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
if (this.sqlDataReader.GetValue(this.index) is T value)
{
return value;
}
}
return default(T);
}
public object GetValue(string column)
{
column.EnsureNotNullOrWhiteSpace(nameof(column));
var colIndex = this.sqlDataReader.GetOrdinal(column);
if (colIndex >= 0 && colIndex < this.sqlDataReader.FieldCount)
{
if (!this.sqlDataReader.IsDBNull(this.index))
{
return this.sqlDataReader.GetValue(this.index);
}
}
return default(object);
}
internal bool Read()
{
this.index = -1;
return this.sqlDataReader.Read();
}
public static implicit operator FluentSQLReader(SqlDataReader sqlDataReader)
=> new FluentSQLReader(sqlDataReader);
}
}