Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF CodeFirst: Get all POCO types for DbContext

Is there any way to get POCO's types from specified DbContext instance?

like image 546
DrAlligieri Avatar asked Sep 23 '12 15:09

DrAlligieri


3 Answers

You need to access the MetadataWorkspace

public class MyContext : DbContext
{

    public void Test()
    {            
        var objectContext = ((IObjectContextAdapter)this).ObjectContext;

        var mdw = objectContext.MetadataWorkspace;

        var items = mdw.GetItems<EntityType>(DataSpace.CSpace);
        foreach (var i in items)
        {
            Console.WriteLine("Class Name: {0}", i.Name);
        }
 }
like image 162
Eranga Avatar answered Sep 19 '22 20:09

Eranga


Unfortunately, I couldn't edit the accepted answers - you just need to change the dataspace used as follows

var items = mdw.GetItems<EntityType>(DataSpace.OSpace);

to get your POCO classes instead of the EF proxies.

like image 31
Anand P Avatar answered Sep 17 '22 20:09

Anand P


@Lei Yang: you can use this to get all types into a list.

var objectContext = ((IObjectContextAdapter) dbContext).ObjectContext;
var mdw = objectContext.MetadataWorkspace;
var items = mdw.GetItems<EntityType>(DataSpace.CSpace);

var dbContextAssembly = dbContext.GetType().Assembly;

var entityTypes = new List<Type>();
foreach (var i in items) {
    entityTypes.Add(dbContextAssembly.GetType(i.FullName));
}
like image 45
Nam Vu Avatar answered Sep 18 '22 20:09

Nam Vu