Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dbsets metadata from EF CodeFirst DbContext?

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.

like image 293
WillC Avatar asked Feb 27 '12 18:02

WillC


1 Answers

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

like image 79
WillC Avatar answered Sep 27 '22 21:09

WillC