检查是否有任何数据库表有任何行

时间:2022-11-26 12:45:50

I am trying to understand how to check if any table in my db has data using entity framework. I can check for one table but how can I check for all tables at once? DO we have any option with ef6?

我试图了解如何检查我的数据库中的任何表是否具有使用实体框架的数据。我可以检查一个表但是如何一次检查所有表?我们对ef6有什么选择吗?

using (var db = new CreateDbContext())
{
    if(!db.FirstTable.Any())
    {
        // The table is empty
    }
}

Any pointers on how to loop through entities would be helpful.

关于如何循环实体的任何指针都会有所帮助。

2 个解决方案

#1


3  

Here is one way you could do this with t-sql. This should be lightning fast on most systems. This returned in less than a second on our ERP database. It stated 421 billion rows in more than 15,000 partition stats.

这是使用t-sql执行此操作的一种方法。在大多数系统中,这应该是快速的。这在我们的ERP数据库中返回不到一秒钟。它表示超过15,000个分区统计数据中有421亿行。

select sum(p.row_count)
from sys.dm_db_partition_stats p
join sys.objects o on o.object_id = p.object_id
where o.type not in ('S', 'IT') --excludes system and internal tables.

#2


1  

Similar to @SeanLange, but shows schema name and table name for tables without any rows.

与@SeanLange类似,但显示没有任何行的表的模式名称和表名称。

SELECT  Distinct OBJECT_SCHEMA_NAME(p.object_id) AS [Schema], 
        OBJECT_NAME(p.object_id) AS [Table]
FROM    sys.partitions p
        INNER JOIN sys.indexes i 
            ON p.object_id = i.object_id
            AND p.index_id = i.index_id
WHERE   OBJECT_SCHEMA_NAME(p.object_id) != 'sys'
        And p.Rows = 0    
ORDER BY [Schema], [Table]

#1


3  

Here is one way you could do this with t-sql. This should be lightning fast on most systems. This returned in less than a second on our ERP database. It stated 421 billion rows in more than 15,000 partition stats.

这是使用t-sql执行此操作的一种方法。在大多数系统中,这应该是快速的。这在我们的ERP数据库中返回不到一秒钟。它表示超过15,000个分区统计数据中有421亿行。

select sum(p.row_count)
from sys.dm_db_partition_stats p
join sys.objects o on o.object_id = p.object_id
where o.type not in ('S', 'IT') --excludes system and internal tables.

#2


1  

Similar to @SeanLange, but shows schema name and table name for tables without any rows.

与@SeanLange类似,但显示没有任何行的表的模式名称和表名称。

SELECT  Distinct OBJECT_SCHEMA_NAME(p.object_id) AS [Schema], 
        OBJECT_NAME(p.object_id) AS [Table]
FROM    sys.partitions p
        INNER JOIN sys.indexes i 
            ON p.object_id = i.object_id
            AND p.index_id = i.index_id
WHERE   OBJECT_SCHEMA_NAME(p.object_id) != 'sys'
        And p.Rows = 0    
ORDER BY [Schema], [Table]