是否有可能从一个通用的 entity.DbSet
中获取 dataTable
我已经尝试过,但是到目前为止获取有效数据的唯一方法是 Local
也许我错过了一个,但我尝试像下面那样解析它
DataSet ds = entityDbSet as DataSet;
但这是不可能的。
我想到的唯一方法是将 entity.dbSet
放在一个列表中,基本上是循环它,但我确信这不是最好的主意。
我会尝试 tolistasync
但我还不知道如何使用它。
最佳答案
接口(interface)不兼容,你不能像那样转换它们。
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
你能做什么,这对你很有帮助:
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
为了保证异步,您的方法必须是异步的,并且转换必须在等待之后完成。
关于c# - 实体泛型 dbSet 获取数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37770211/