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

71 lines
1.8 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 SQLReader(SqlDataReader sqlDataReader)
=> this.sqlDataReader = sqlDataReader;
public void Dispose()
{
this.sqlDataReader.Close();
this.sqlDataReader.Dispose();
}
public T GetValue<T>(int index)
{
if (!this.sqlDataReader.IsDBNull(index))
{
var value = this.sqlDataReader.GetValue(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 T GetValue<T>(string column)
{
var table = this.sqlDataReader.GetSchemaTable();
if (table?.Columns?.Contains(column) == true)
{
var index = this.sqlDataReader.GetOrdinal(column);
return this.GetValue<T>(index);
}
return default(T);
}
internal bool Read()
=> this.sqlDataReader.Read();
public static implicit operator SQLReader(SqlDataReader sqlDataReader)
=> new SQLReader(sqlDataReader);
}
}