【问题标题】:Get Types Collection from EntityFramework ObjectContext从 EntityFramework ObjectContext 获取类型集合
【发布时间】:2009-07-26 10:17:54
【问题描述】:

如何从ObjectContext 中提取Types 的列表?

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

我该怎么做?

【问题讨论】:

    标签: c# .net entity-framework


    【解决方案1】:

    我假设您在运行时想要查询生成的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&lt;T&gt; 的公共属性,其中TEntityObject 的子类。

    【讨论】:

    • 在EF4.0中,只有去掉这行:&& propertyType.Name == "ObjectQuery`1",结果才会ok,否则什么都不返回。你能解释一下吗?
    • 你可以在你的上下文中有类型,在上下文中没有 DbSet 属性,不是吗?
    【解决方案2】:

    如果您使用的是动态数据,这会变得更容易,我只是在我们的一个应用中这样做了

    MetaModel.GetModel(objectContext.GetType()).Tables.Select(t => t.EntityType);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 2015-03-21
      • 2013-05-20
      相关资源
      最近更新 更多