I have this method for creating DataTable
:
private DataTable toDataTable<T>(IEnumerable<T> items)
{
var tb = new DataTable(typeof(T).Name);
using (var context = new MyEntity())
{
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
tb.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (var item in items)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
}
return tb;
}
but it give me this error in second foreach
:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
since I opened my EF's context
;why again this error occurs?
The IEnumerable<T>
that you are passing into toDataTable<T>()
has not been realized yet. The context of items
is already disposed. You have forgotten a ToList()
in the calling code.