Is it possible to get dataTable
from a generic entity.DbSet
i have tried but the only way to get data that worked so far is the Local
maybe i missed one but i tried parsing it like below
DataSet ds = entityDbSet as DataSet;
but it's not possible.
The only way i am thinking of is putting the entity.dbSet
in a list, basically looping it but i am sure it's not the best idea.
i would try tolistasync
but i didn't figure out yet how to use it.
Asked
Active
Viewed 5,690 times
4

I_Tried_Thats_Why_Im_Here
- 63
- 1
- 11
1 Answers
3
The interfaces are not compatible and you cannot not just cast them like that.
public class DbSet<TEntity> : DbQuery<TEntity>, IDbSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable, IInternalSetAdapter where TEntity : class
public class DataSet : MarshalByValueComponent, System.ComponentModel.IListSource, IXmlSerializable, ISupportInitializeNotification, ISerializable
What you can do and this will be very helpful for you:
var users = dbContext.Users.ToListAsync().Result.ToDataTable();
public static class DataTableExtensions
{
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
Convert DbContext to Datatable in Code first entity framework
To guarantee the asynchronous your method have to be async and the converting must done after the awaiting.

Community
- 1
- 1

Bassam Alugili
- 16,345
- 7
- 52
- 70