How to get all DbSet from DbContext

c# entity-framework

Question

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?

1
5
2/4/2016 5:05:25 PM

Accepted Answer

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

12
8/18/2018 4:11:00 PM

Popular Answer

 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>();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow