为何成功执行的DBCC CHECKIDENT会抛出SqlException异常?
This issue boils down to how SQL Server and Entity Framework handle informational messages:
The Root Cause
When you run DBCC CHECKIDENT, SQL Server automatically returns an informational message (the exact text you're seeing in your exception: "Checking identity information: current identity value '', current column value ''. DBCC execution completed...").
Entity Framework's ExecuteSqlCommand method treats all messages returned by SQL Server (including non-error informational ones) as errors, which triggers the SqlException—even though the DBCC operation itself succeeded perfectly.
The Fix
The simplest and most reliable solution is to modify your DBCC command in the stored procedure to suppress these informational messages using the WITH NO_INFOMSGS option:
if exists (select * from import.table) begin delete import.table DBCC CHECKIDENT ('import.table', RESEED, 0) WITH NO_INFOMSGS; -- Add this clause end
This option tells SQL Server not to send the post-execution informational message, so EF won't pick up any "errors" to throw an exception for.
If you can't modify the stored procedure for some reason, you'd need to use a lower-level SqlCommand approach instead of EF's ExecuteSqlCommand, where you can configure the command to ignore informational messages. But modifying the DBCC command is the cleanest fix here.
内容的提问来源于stack exchange,提问作者Muflix

