EF6 动态获取表

EF6 get tables dynamicly

我首先将 Entity Framework 6 与数据库一起使用。尝试显示有关每个 table (DbSet) 的信息,包括条目数。 最后,我想显示我的 DbContext 中任何选定的 table 的某些(前 200)行。我试图在没有硬编码特定类型的情况下使用反射来实现这一点。

using (MyDataEntities pd = new MyDataEntities())
{
    var metadata = ((IObjectContextAdapter)pd).ObjectContext.MetadataWorkspace;

    var tables = metadata.GetItemCollection(DataSpace.SSpace)
        .GetItems<EntityContainer>().Single().BaseEntitySets.OfType<EntitySet>()
        .Where(s => !s.MetadataProperties.Contains("Type")
        || s.MetadataProperties["Type"].ToString() == "Tables").ToList();

    // This is working.
    var set = pd.GetType().GetProperty("MyType1").GetValue(pd);
    var theSet = set as DbSet<MyType1>;

    if (theSet != null)
    {
        int count = theSet.Count();     // This is working.
        var rows = theSet.ToList();     // This is working.
    }
          
    foreach (var t in tables)
    {
        dynamic dbset = pd.GetType().GetProperty(t.Name).GetValue(pd);
        int count = dbset.Count();      // This is not working
        var rows = dbset.ToList();      // This is not working
    }
}

我收到异常:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:''System.Data.Entity.DbSet<MyAppName.MyType1>' does not contain a definition for 'Count''

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:''System.Data.Entity.DbSet<MyAppName.MyType1>' does not contain a definition for 'ToList''

这甚至可能是我正在尝试的吗?

我将动态值转换为 IQueryable,从那里它可以像查询一样使用。

foreach (var t in tables)
{
    dynamic dbset = pd.GetType().GetProperty(t.Name).GetValue(pd);
    var query = dbset as IQueryable;
    var result = query.ToListAsync().Result;
                 

    int count = result.Count();      // This is working
    var rows = result.ToList();      // This is working
}