c# - 使用字符串从上下文中获取表

标签 c# entity-framework reflection

我正在尝试将 Entity Framework 上下文与表名一起传递给表单构造函数,但我无法从上下文中获取表对象。 BindingSource 的数据源应该设置为该表的数据,DataGridView 的数据源绑定(bind)到 BindingSource。

任何人都可以帮助将表数据放入 tableName 类型的列表并填充 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

关于c# - 使用字符串从上下文中获取表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919355/

相关文章:

c# - 调用嵌入在 Winforms-Application 中的 Unity-Application 上的函数

c# - MenuItem 背景不透明度而不是其文本?

c# - 如何使用 EF Core 2.1.0 和代理进行延迟加载

go - 获取基于原始类型的类型的reflect.Kind

c# - RouteConfig 设置接受可选参数

c# - 将数组从可空类型转换为相同类型的不可空类型?

c# - 使用继承时设置外键关联的正确方法

c# - 提供类作为保存数据的服务的正确方法是什么?

c# - 如何在 C# 中使用 System.Reflection.MethodBase 查找方法的返回类型?

c# - TargetInvocationException @ PropertyInfo.GetValue(target, null) 与目标类型 MemoryStream