如何从Types提取ObjectContext列表?

例如,我有一个对象上下文,其中包含一个名为“银行”的实体和一个名为“公司”的实体。
我想获取它们的EntityObject类型。

我怎样才能做到这一点?

最佳答案

我假设您在运行时想查询生成的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的子类。

10-07 22:59