public static EntityType GetObjectSpaceEntityByType <T>(this MetadataWorkspace metadataWorkspace) { ObjectItemCollection objectItemCollection = (ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace); EntityType entityType = objectItemCollection.GetItems <EntityType>() .FirstOrDefault(x => objectItemCollection.GetClrType(x) == typeof(T)); return(entityType); }
/// <summary> /// Gets entity type by CLR type. /// </summary> /// <param name="ctx">Context instance</param> /// <param name="type">Type to get EntityType for</param> /// <returns><see cref="EntityType"/> instance if type is an entity type, null otherwise.</returns> public static EntityType GetEntityType(this DbContext ctx, Type type) { // Will not work for EF Core: https://stackoverflow.com/a/37651883 // should use context.Model, then model.FindEntityType(source.Type) ObjectItemCollection objectItemCollection = (ObjectItemCollection)((IObjectContextAdapter)ctx).ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.OSpace); ReadOnlyCollection <EntityType> entityTypes = objectItemCollection.GetItems <EntityType>(); return(entityTypes.FirstOrDefault(et => objectItemCollection.GetClrType(et) == type)); }
/// <summary> /// Populates the ComplexTypes and GeneratedComplexTypes dictionaries from the MetadataWorkspace. /// </summary> private void PopulateComplexTypesInObjectContext() { ObjectItemCollection itemCollection = this.MetadataWorkspace.GetItemCollection(DataSpace.OSpace) as ObjectItemCollection; foreach (ComplexType objectSpaceEntityType in itemCollection.GetItems <ComplexType>()) { Type clrType = itemCollection.GetClrType(objectSpaceEntityType); StructuralType edmComplexType; if (this.MetadataWorkspace.TryGetEdmSpaceType(objectSpaceEntityType, out edmComplexType)) { this.ComplexTypes[(ComplexType)edmComplexType] = clrType; } } }
/// <summary> /// Gets a dictionary of all entity types associated with the current DbContext type. /// The key is the EntityType (CSpace) and the value is the CLR type of the generated entity. /// </summary> /// <returns>A dictionary keyed by entity type and returning corresponding CLR type</returns> private Dictionary <EntityType, Type> GetEntityTypesInContext() { Dictionary <EntityType, Type> entities = new Dictionary <EntityType, Type>(); ObjectItemCollection itemCollection = this.MetadataWorkspace.GetItemCollection(DataSpace.OSpace) as ObjectItemCollection; foreach (EntityType objectSpaceEntityType in itemCollection.GetItems <EntityType>()) { Type clrType = itemCollection.GetClrType(objectSpaceEntityType); // Skip the EF CodeFirst specific EdmMetadata type if (DbContextUtilities.CompareWithSystemType(clrType, BusinessLogicClassConstants.EdmMetadataTypeName)) { continue; } StructuralType edmEntityType; if (this.MetadataWorkspace.TryGetEdmSpaceType(objectSpaceEntityType, out edmEntityType)) { entities[(EntityType)edmEntityType] = clrType; } } return(entities); }