c# - 从 EntityFramework ObjectContext 获取类型集合

标签 c# .net entity-framework

如何从 ObjectContext 中提取 Types 列表?

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

我该怎么做?

最佳答案

我假设您在运行时想要查询生成的 ObjectContext获取 EntityObject 列表的类类。然后它变成了反射(reflection)练习:

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> 的对象上下文中找到所有公共(public)属性其中 TEntityObject 的子类.

关于c# - 从 EntityFramework ObjectContext 获取类型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1184208/

相关文章:

c# - 即使没有请求参数,Web API 参数绑定(bind)也返回实例

c# - Entity Framework 中的准备语句

c# - EF 保存到上下文但不保存到数据源

asp.net-mvc - EntityFramework.SqlServer 未部署在 Web 发布中

c# - 使用 C# 将大量或行写入 mssql 数据库

c# - 是否可以根据 API 端点所在的服务器来禁用它?

c# - 在基于.NET Framework 2.0的项目中使用.NET Framework 3.5库添加LINQ To XML功能

c# - 如何为 Microsoft 的 .NET 4 C# 编译器指定 .NET 版本?

c# - comboBox 中的 selectedIndex 在某些情况下不返回正确的整数

entity-framework - 使用 F# 和 ASP.NET MVC 保存 EF