我试图在实体框架上下文中传递给表单构造器以及表名称,但我一直试图从上下文中获取表对象。BindingSource的数据源应该被设置为该表的数据,DataGridView的数据源被绑定到BindingSource。
有谁能帮我把表数据放入tableName类型的List中并填充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;
}
谢谢。
那么,您可以使用上下文中的元数据做这样的事情:
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;
}
旁注:我假设你的T
泛型类型有这样的泛型约束:
public class YourContextWrapper<T> where T:DbContext