'How to get all DbSet from DbContext
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?
Solution 1:[1]
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
Solution 2:[2]
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>();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | VinÃcius Todesco |