6

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
  • There are no such methods in Core. You could however use a raw query. Though if you explain the use case there might be other approaches
    – TheGeneral
    Nov 21, 2020 at 23:33
  • we just want to display all the database in a report with EF Core, I believe raw sql is select * from sys.tables, or informatioin_schema.tables, however looking for EFCore way, cc @TheGeneral
    – user14683773
    Nov 22, 2020 at 0:55

2 Answers 2

16

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy