I am using Entity Framework 6 with database first. Trying to display information about each table (DbSet
), including number of entries. Eventually, I want to display some (TOP 200) rows of any selected table from my DbContext
. I tried to achieve that using reflection without hard-coded specific types.
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
}
}
I am getting exceptions:
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''
Is this even possible what I am trying?
Aucun commentaire:
Enregistrer un commentaire