Created
March 5, 2022 01:40
-
-
Save IgnacioCastro0713/6664c0d68d02e791a8505fd28487412e to your computer and use it in GitHub Desktop.
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; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Data.Common; | |
using System.Linq; | |
namespace Extensions | |
{ | |
public static class DataReaderExtension | |
{ | |
public static async IAsyncEnumerable<T> MapperAsync<T>(this DbDataReader reader) where T : class, new() | |
{ | |
if (reader is { HasRows: false }) yield break; | |
while (await reader.ReadAsync()) | |
{ | |
yield return reader.MapObject<T>(); | |
} | |
} | |
private static T MapObject<T>(this IDataRecord reader) where T : class, new() | |
{ | |
var type = typeof(T); | |
var propertyInfos = type.GetProperties().ToDictionary(info => info.Name.ToUpper()); | |
var objectType = new T(); | |
for (var index = 0; index < reader.FieldCount; index++) | |
{ | |
var key = reader.GetName(index).ToUpper(); | |
if (propertyInfos.TryGetValue(key, out var propertyInfo) && propertyInfo.CanWrite) | |
{ | |
propertyInfo.SetValue(objectType, reader.GetValueOrDefault(index, propertyInfo.PropertyType), null); | |
} | |
} | |
return objectType; | |
} | |
private static object GetValueOrDefault(this IDataRecord reader, int index, Type propertyType) => | |
reader.IsDBNull(index) | |
? null | |
: Convert.ChangeType(reader.GetValue(index), propertyType); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment