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 Answer
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
2 Comments
WillC
I figured out how to reference the Entities in the DbContext but I am still uncertain how to get that reference in the T4 template that I am using for the code generation. Any ideas? I will probably post another question on that issue.
Juan Pablo Gomez
Did you found the T4 Solution ?