EF CodeFirst: Get all POCO types for DbContext

2020-06-17 05:13发布

问题:

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

回答1:

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);
        }
 }


回答2:

@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));
}


回答3:

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.