【问题标题】:Entity Framework Core: Get a List of All the TablesEntity Framework Core:获取所有表的列表
【发布时间】:2020-11-21 23:18:28
【问题描述】:

如何在 db 上下文中获取 Entity Framework Core 中所有表的列表?

以下答案适用于 Entity Framework 5 中的先前版本,我们目前使用的是 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();

我们只想使用 EF Core 在报告中显示所有数据库。原始 Sql 是select * from sys.tables or information_schema.tables,但是正在寻找 EFCore 方式

【问题讨论】:

  • Core 中没有这样的方法。但是,您可以使用原始查询。虽然如果您解释用例,可能还有其他方法
  • 我们只想用 EF Core 在报告中显示所有数据库,我相信原始 sql 是 select * from sys.tables 或 informationatioin_schema.tables,但是寻找 EFCore 方式,cc @TheGeneral

标签: c# entity-framework asp.net-core .net-core entity-framework-core


【解决方案1】:

数据库中所有表的列表 - 没有。映射到上下文的所有实体的列表以及有关其数据库映射(表、列、索引等)的信息 - 当然。您将使用比 EF 更直观的 EF Core 元数据 API。从DbContextModel 属性开始,探索可用的(扩展)方法。

例如:

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

【讨论】:

【解决方案2】:

您可以尝试使用 EFCore 脚手架的内部结构来检索所有表

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

如下:

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. 

这目前适用于 EFCore 5.07,并且 sqllite 尚未与其他提供程序进行测试。与往常一样,当利用内部结构时,请注意升级 EFCore 可能会破坏这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2022-07-05
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多