Skip to content

Instantly share code, notes, and snippets.

@Comfie
Forked from jchadwick/DynamicSqlDataReader.cs
Created November 9, 2022 13:16
Show Gist options
  • Save Comfie/44ed5a6a9f1c05f3d33ccacb6b0fbb14 to your computer and use it in GitHub Desktop.
Save Comfie/44ed5a6a9f1c05f3d33ccacb6b0fbb14 to your computer and use it in GitHub Desktop.
A helper class to read SQL results into a dynamic object
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Dynamic;
public class DynamicSqlDataReader
{
private static dynamic ToExpando(IDataRecord record)
{
var expandoObject = new ExpandoObject() as IDictionary<string, object>;
for (var i = 0; i < record.FieldCount; i++)
expandoObject.Add(record.GetName(i), record[i]);
return expandoObject;
}
public IEnumerable<dynamic> Read(SqlDataReader reader)
{
while (reader.Read())
{
yield return ToExpando(reader);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment