I used the following extension with Entity Framework models, it would work with any type of collection :
public static System.Data.DataTable ToDataTable<T>(this IEnumerable<T> source)
{
var table = new System.Data.DataTable(typeof(T).Name);
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (var item in source)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
table.Rows.Add(values);
}
return table;
}
and applying it to your sample code would be like this :
var dt= new BiblioEntities().Adhérent.SqlQuery(@"select * from Adhérent ").ToDataTable();