laatzen/LaaProductionWeb/LaaProduction.Data.SQL/SQLReader.cs
2024-04-22 09:00:01 +02:00

80 lines
1.9 KiB
C#

namespace LaaProduction.Data.SQL
{
using LaaProduction.Data.SQL.Interfaces;
using System;
using System.Data.SqlClient;
public class SQLReader : ISQLReader, IDisposable
{
private readonly SqlDataReader sqlDataReader;
private int index;
private SQLReader(SqlDataReader sqlDataReader)
=> this.sqlDataReader = sqlDataReader;
public void Dispose()
{
this.sqlDataReader.Close();
this.sqlDataReader.Dispose();
}
public T GetValue<T>()
{
this.index++;
if (!this.sqlDataReader.IsDBNull(this.index))
{
var value = this.sqlDataReader.GetValue(this.index);
var type = Nullable.GetUnderlyingType(typeof(T));
if (type is null)
{
type = typeof(T);
}
try
{
value = Convert.ChangeType(value, type);
}
catch (Exception)
{
// TODO:
}
if (value is T _value)
{
return _value;
}
}
return default(T);
}
public object GetValue(string column)
{
var colIndex = this.sqlDataReader.GetOrdinal(column);
if (0 <= colIndex && colIndex < this.sqlDataReader.FieldCount)
{
if (!this.sqlDataReader.IsDBNull(colIndex))
{
return this.sqlDataReader.GetValue(colIndex);
}
}
return default(object);
}
internal bool Read()
{
this.index = -1;
return this.sqlDataReader.Read();
}
public static implicit operator SQLReader(SqlDataReader sqlDataReader)
=> new SQLReader(sqlDataReader);
}
}