7

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

  • 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 '20 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 –  Nov 22 '20 at 00:55

2 Answers2

17

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();
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • hi maybe you can help out with this question? thanks https://stackoverflow.com/questions/65031605/entity-framework-get-the-datatype-of-metadata-iproperty –  Nov 27 '20 at 03:07
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.

beats
  • 93
  • 4