Skip to content

Instantly share code, notes, and snippets.

@jchadwick
Created September 20, 2012 13:18
Show Gist options
  • Save jchadwick/3755847 to your computer and use it in GitHub Desktop.
Save jchadwick/3755847 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);
}
}
}
@pamanes
Copy link

pamanes commented Jan 7, 2016

Can you iterate through it after the SqlDataReader is closed?
thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment