Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the list of entity types from an ObjectContext at runtime using EF code first?

I'm trying to write some extensions on top of EF and I need to be able to inspect a code first ObjectContext and retrieve the entity types in it. I feel like this should be available somewhere in the metadata workspace, but I'm not sure where to look. I'm using EF 5.

Note that we don't use any kind of code generation to create our contexts, nor do we put type-specific DbSet accessors on the DbContext base class. Thus, I can't simply reflect over the DbContext/ObjectContext to look that such properties.

like image 613
ChaseMedallion Avatar asked Sep 23 '13 01:09

ChaseMedallion


1 Answers

I think this should work:

var objectItemCollection = 
   (ObjectItemCollection )((IObjectContextAdapter)ctx)
   .ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.OSpace);

foreach(var entityType in objectItemCollection.GetItems<EntityType>())
{
    Console.WriteLine(objectItemCollection.GetClrType(entityType).FullName);
}
like image 135
Pawel Avatar answered Oct 17 '22 00:10

Pawel