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.