Created
May 2, 2024 07:58
-
-
Save Xor-el/8ba85c60d859a93cfa09583e687a6a22 to your computer and use it in GitHub Desktop.
DbDataReaderExtensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Data.Common; | |
using System.Reflection; | |
namespace Demo.Extensions | |
{ | |
public static class DbDataReaderExtensions | |
{ | |
public static T? Map<T>(this DbDataReader reader) where T : class, new() | |
{ | |
// Check if the reader has rows | |
if (reader.HasRows) | |
{ | |
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); | |
_ = reader.Read(); | |
T instanceToPopulate = new(); | |
foreach (var property in properties) | |
{ | |
var attribute = Attribute.GetCustomAttribute(property, typeof(DataFieldAttribute)) as DataFieldAttribute; | |
string columnName = attribute is not null ? attribute.Name : property.Name; | |
if (!reader.IsDBNull(reader.GetOrdinal(columnName))) | |
{ | |
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; | |
var safeValue = Convert.ChangeType(reader[columnName], type); | |
property.SetValue(instanceToPopulate, safeValue, null); | |
} | |
} | |
return instanceToPopulate; | |
} | |
return null; | |
} | |
public static List<T> MapToList<T>(this DbDataReader reader) where T : class, new() | |
{ | |
var list = new List<T>(); | |
// Check if the reader has rows | |
if (reader.HasRows) | |
{ | |
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); | |
while (reader.Read()) | |
{ | |
T instanceToPopulate = new(); | |
foreach (var property in properties) | |
{ | |
var attribute = Attribute.GetCustomAttribute(property, typeof(DataFieldAttribute)) as DataFieldAttribute; | |
string columnName = attribute is not null ? attribute.Name : property.Name; | |
if (!reader.IsDBNull(reader.GetOrdinal(columnName))) | |
{ | |
var t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; | |
object safeValue = Convert.ChangeType(reader[columnName], t); | |
property.SetValue(instanceToPopulate, safeValue, null); | |
} | |
} | |
list.Add(instanceToPopulate); | |
} | |
} | |
return list; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment