Reputation: 588
I need to get all tables in the database using EF. I need them to go table by table and extract certain information from each. Any idea how?
Upvotes: 12
Views: 24280
Reputation: 11327
Here is the extension method I use in my EntityFramework Plus library.
using (var ctx = new TestContext())
{
var dbSetProperties = ctx.GetDbSetProperties();
List<object> dbSets = dbSetProperties.Select(x => x.GetValue(ctx, null)).ToList();
}
public static class Extensions
{
public static List<PropertyInfo> GetDbSetProperties(this DbContext context)
{
var dbSetProperties = new List<PropertyInfo>();
var properties = context.GetType().GetProperties();
foreach (var property in properties)
{
var setType = property.PropertyType;
#if EF5 || EF6
var isDbSet = setType.IsGenericType && (typeof (IDbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()) || setType.GetInterface(typeof (IDbSet<>).FullName) != null);
#elif EF7
var isDbSet = setType.IsGenericType && (typeof (DbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()));
#endif
if (isDbSet)
{
dbSetProperties.Add(property);
}
}
return dbSetProperties;
}
}
Edit You need to use reflection from the DbSet element type and iterate over all properties. This will not work with TPC, TPT and TPH
For a simpler solution, use the method GetModel from Entity Framework Extensions. This is a FREE feature of this library.
Project: Entity Framework Extensions
Documentation: GetModel
Disclaimer: I'm the owner of the project Entity Framework Extensions
Upvotes: 23
Reputation: 1897
EntityContainer container = ObjectContext.MetadataWorkspace.GetEntityContainer(ObjectContext.DefaultContainerName, DataSpace.CSpace);
List<string> result = (from meta in container.BaseEntitySets
where meta.BuiltInTypeKind == BuiltInTypeKind.EntitySet
select meta.ElementType.ToString()).ToList<string>();
Upvotes: 0