2
votes

I am trying to pass in an Entity Framework context to a forms constructor along with a table name, but am stuck trying to get the table object from the context. A BindingSource's datasource should be set to this table's data, DataGridView's DataSource is bound to the BindingSource.

Can anyone help with getting the table data into let's say a List of type tableName and populating the dgv?

public MyForm(T context, string tableName)
{
    // use reflection to get the table data from context?

    // Doesnt work:
    var table = context.GetType().GetProperties().FirstOrDefault(x=>x.Name == tableName);
    bindingSource.DataSource = table; //?????
    dgvDataviewer.DataSource  = bindingSource;
}

Thanks.

1
What is not working about this? Is it not finding the property? Does the table name match the property name? EF defaults table names to plural, which may not match your properties. - Max
It's not returning the data from the table. Yes the names match, I'm sure there's just a step I'm missing but I can't figure it out. Maybe the answer is in GetGetMethod and invoking that some how? - cdsln
table should be a PropertyInfo, so you'll need to pull the data out. Invoking the GetGetMethod will get you a DbSet<TableType>, which you can then use more reflection to pull out the values. - Max
Instead of passing the table name, make the class generic and pass the entity type when you call the constuctor, ie new MyForm<MyEntity>(). You can get the table itself using DbContext.Set<T>() or even DbContext.Set(Type) - Panagiotis Kanavos

1 Answers

0
votes

Well, you can do something like this using the metadata from your context:

public MyForm(T context, string tableName)
{
     ObjectContext objectContext = ((IObjectContextAdapter)breezeContext).ObjectContext;
     var items= objectContext.MetadataWorkspace
                             .GetItems(System.Data.Entity.Core.Metadata.Edm.DataSpace.CSpace)
                             .Where(b => b.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                             .ToList();
     var dbSetPropertyType = breezeContext.GetType()
                                          .GetProperties()
                                          .FirstOrDefault(x => x.Name == tablename);// tablename must match with the DbSet property in your context
     var dbset = breezeContext.Set(dbSetPropertyType.PropertyType.GenericTypeArguments.FirstOrDefault());

    bindingSource.DataSource = dbset;
    dgvDataviewer.DataSource  = bindingSource;
}

Side Note: I'm supposing your T generic type have a generic constraint like this:

public class YourContextWrapper<T> where T:DbContext