从EntityFramework ObjectContext获取类型集合

3

如何从ObjectContext中提取Types列表?

例如,我有一个包含名为“Bank”和“Company”的实体的对象上下文。 我想获取它们的EntityObject类型。

我该怎么做?

2个回答

5

我假设您在运行时想要查询生成的 ObjectContext 类,以获取 EntityObject 类的列表。这时就需要进行反射操作:

PropertyInfo[] propertyInfos = objectContext.GetType().GetProperties();
IEnumerable<Type> entityObjectTypes =
  from propertyInfo in propertyInfos
  let propertyType = propertyInfo.PropertyType
  where propertyType.IsGenericType
    && propertyType.Namespace == "System.Data.Objects"
    && propertyType.Name == "ObjectQuery`1"
    && propertyType.GetGenericArguments()[0].IsSubclassOf(typeof(EntityObject))
  select propertyType.GetGenericArguments()[0];

这段代码将查找对象上所有的公共属性,这些属性类型为 System.Data.Objects.ObjectQuery<T>,其中 TEntityObject 的子类。

在EF4.0中,只有在删除这一行:&& propertyType.Name == "ObjectQuery`1",结果才会正常,否则返回空值。你能解释一下吗? - Lei Yang
在您的上下文中,可能会有一些类型,在上下文中没有DbSet属性,不是吗? - MBoros

0
如果你正在使用动态数据,这将变得更容易。我刚在我们的一个应用程序中做到了这一点。
MetaModel.GetModel(objectContext.GetType()).Tables.Select(t => t.EntityType);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接