Entity Framework Core: Get a List of All the Tables

Viewed 6814

How do I get a list of all the tables in Entity Framework Core in a db context?

The following answer is for previous version in Entity Framework 5, we are currently using EF Core 3.

how to get a list of all entities in EF 5?

Entity Framework - Get List of Tables

var tableNames = context.MetadataWorkspace.GetItems(DataSpace.SSpace)
                        .Select(t => t.Name)
                        .ToList();

We just want to display all the database in a report with EF Core. Raw Sql is select * from sys.tables or information_schema.tables, however looking for EFCore way

2 Answers

The list of all tables in the database - no. The list of all entities mapped to a context and information about their database mappings (tables, columns, indexes etc.) - sure. You would use the EF Core metadata API which is much more intuitive than EF ones. Start with Model property of the DbContext and explore the available (extension) methods.

For instance:

var tableNames = context.Model.GetEntityTypes()
    .Select(t => t.GetTableName())
    .Distinct()
    .ToList();

You could try using the internals of EFCore scaffolding to retrieve all the tables

https://github.com/dotnet/efcore/blob/v5.0.7/src/EFCore.Design/Scaffolding/Internal/ReverseEngineerScaffolder.cs

such as the below:

var serviceCollection = new ServiceCollection()
                    .AddEntityFrameworkSqlite()
                    .AddLogging()
                    .AddEntityFrameworkDesignTimeServices()
                    .AddSingleton<LoggingDefinitions, SqliteLoggingDefinitions>()                                              
                    .AddSingleton<IDatabaseModelFactory, SqliteDatabaseModelFactory>()                                   
                    .BuildServiceProvider();
    
                var model = serviceCollection.GetRequiredService<IDatabaseModelFactory>();
                var dbOptions = new DatabaseModelFactoryOptions();
                var databaseModelFactory = model.Create(**Put connectionstring here**, dbOptions);

var tables = databaseModelFactory.Tables; //Contains all the tables. 

This currently works with EFCore 5.07 and sqllite not tested this with other providers yet. As always, when tapping into internals be warned that upgrading EFCore could break this.

Related