There is a MetadataWorkspace
class which provides API to retrieve metadata about storage, model, CLR types and mappings for Entity Framework.
Represents the ADO.NET metadata runtime service component that
provides support for retrieving metadata from various sources.
Having an instance of DbContext
, you can find its MetadataWorkspace
using following code:
var metadataWorkspace = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace;
Then you can get item collections which contain different types of models including object model, the conceptual model, the storage (database) model, and the mapping model between the conceptual and storage models.
The following extension methods returns EntityType
for given clr type:
using System;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;
public static class DbContextExtensions
{
public static EntityType GetEntityMetadata<TEntity>(this DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException(nameof(dbContext));
var metadataWorkspace = ((IObjectContextAdapter)dbContext)
.ObjectContext.MetadataWorkspace;
var itemCollection = ((ObjectItemCollection)metadataWorkspace
.GetItemCollection(DataSpace.OSpace));
var entityType = metadataWorkspace.GetItems<EntityType>(DataSpace.OSpace)
.Where(e => itemCollection.GetClrType(e) == typeof(TEntity)).FirstOrDefault();
if (entityType == null)
throw new Exception($"No entity mapped to CLR type '{typeof(TEntity)}'.");
return entityType;
}
}
Then you can use EntityType
to extract more information about the model, for example you can find a list of key properties:
var keys = dbcontext.GetEntityMetadata<Category>().KeyProperties.Select(x=>x.Name).ToList();