14

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 1

16

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Did you found the T4 Solution ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.