c# - 实体泛型 dbSet 获取数据表

标签 c# entity-framework generics

是否有可能从一个通用的 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/

相关文章:

java - 类型中的方法不适用于参数

c# - 当类是通用的时找不到 Web API Controller

c# - 如何使用 TPL 在 C# 中编码(marshal)对特定线程的调用

c# - 逻辑现在是多态而不是 Switch,但是构造呢?

wpf - 使用 Entity Framework 和 IDataErrorInfo 进行业务逻辑验证

c# - 如果我将 virtual 关键字添加到属性,我需要帮助解决为什么 Entity Framework 不会保存

asp.net - 使用 EntityDataSource 进行联接

c# - 更多的 CPU/核心是否有助于缩短 VS.NET 的构建时间?

c# - 无法自动进入服务器。连接到服务器机器 "abc"失败

java - 为什么 List<generic> 在 mybatis 与 java 的情况下不起作用?