Skip to content

Instantly share code, notes, and snippets.

@igoventura
Created July 26, 2019 21:05
Show Gist options
  • Save igoventura/8af8e03ee7dc4201bb9854735d78384d to your computer and use it in GitHub Desktop.
Save igoventura/8af8e03ee7dc4201bb9854735d78384d to your computer and use it in GitHub Desktop.
Map sql query c#
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Reflection;
namespace EFCore.ProceduresSchema.Extensions
{
// ReSharper disable once InconsistentNaming
public static class DbDataReader_
{
/// <Summary>
/// Map data from DataReader to list of objects
/// </Summary>
/// <typeparam name="T">Object</typeparam>
/// <param name="dr">Data Reader</param>
/// <returns>List of objects having data from data reader</returns>
public static List<T> MapToList<T>(this DbDataReader dr) where T : new()
{
List<T> retVal = null;
var entity = typeof(T);
if (dr == null || !dr.HasRows) return null;
retVal = new List<T>();
var props = entity.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propDict = props.ToDictionary(p => p.Name.ToUpper(), p => p);
while (dr.Read())
{
var newObject = new T();
for (var index = 0; index < dr.FieldCount; index++)
{
if (!propDict.ContainsKey(dr.GetName(index).ToUpper())) continue;
var info = propDict[dr.GetName(index).ToUpper()];
if ((info == null) || !info.CanWrite) continue;
var val = dr.GetValue(index);
info.SetValue(newObject, (val == DBNull.Value) ? null : val, null);
}
retVal.Add(newObject);
}
return retVal;
}
/// <Summary>
/// Map data from DataReader to an object
/// </Summary>
/// <typeparam name="T">Object</typeparam>
/// <param name="dr">Data Reader</param>
/// <returns>Object having data from Data Reader</returns>
public static T MapToSingle<T>(this DbDataReader dr) where T : new()
{
var retVal = new T();
var entity = typeof(T);
if (dr == null || !dr.HasRows) return retVal;
var props = entity.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propDict = props.ToDictionary(p => p.Name.ToUpper(), p => p);
dr.Read();
for (var index = 0; index < dr.FieldCount; index++)
{
if (!propDict.ContainsKey(dr.GetName(index).ToUpper())) continue;
var info = propDict[dr.GetName(index).ToUpper()];
if ((info == null) || !info.CanWrite) continue;
var val = dr.GetValue(index);
info.SetValue(retVal, (val == DBNull.Value) ? null : val, null);
}
return retVal;
}
}
}
try
{
var command = _context.Database.GetDbConnection().CreateCommand();
command.CommandText = "select * from tabela where codigo = 123";
using (var result = await command.ExecuteReaderAsync())
{
return result.MapToList<T>();
}
}
catch (Exception ex)
{
throw ex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment