How to get dbsets metadata from EF CodeFirst DbContext?

后端 未结 1 607
野的像风
野的像风 2020-12-29 10:17

How do you programatically get the metadata for the dbset classes from an EF CodeFirst dbcontext? This is to loop through for code generation purposes.

相关标签:
1条回答
  • 2020-12-29 10:49

    After some additional research, I think I found an answer. Basically, you have to drop down into the ObjectContext, the original EF context that DbContext is a wrapper for, and use the MetadataWorkspace information below.

    Please add another answer if there is a direct way to get this directly from the DbContext as it would be more intuitive and preferable if there is one.

    using System.Data.Metadata.Edm;
    using System.Data.Objects;
    using System.Data.Entity.Infrastructure;
    
    ...
    
    using (dbcontext context = new TestContext())
    {
       ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
       MetadataWorkspace workspace = objContext.MetadataWorkspace;
       IEnumerable<EntityType> tables = workspace.GetItems<EntityType>(DataSpace.SSpace);
    
    }
    

    Thanks, Will

    0 讨论(0)
提交回复
热议问题