EF CodeFirst: Get all POCO types for DbContext

2020-06-17 05:30发布

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

3条回答
The star\"
2楼-- · 2020-06-17 06:00

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.

查看更多
闹够了就滚
3楼-- · 2020-06-17 06:11

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);
        }
 }
查看更多
Viruses.
4楼-- · 2020-06-17 06:14

@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));
}
查看更多
登录 后发表回答