Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 565
Richard Avatar asked Feb 04 '16 17:02

Richard


People also ask

Is DbSet part of DbContext?

The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views. Adds the given entity to the context with the Added state.

What is the difference between DbSet and DbContext?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.

How can I tell entity framework to save changes only for a specific DbSet?

Initially you find all entities whose state is not unchanged and save their entry. Then you set the state of every entity that isn't of your type TEntity and set their state to unchanged. Then call the base. SaveChanges() to save all changes to entities of your type.


1 Answers

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

like image 171
Jonathan Magnan Avatar answered Oct 21 '22 15:10

Jonathan Magnan