Skip to main content
 首页 » 编程设计

c#之Entity Framework 连接无法识别创建的临时表

2024年02月23日15txw1958

我有一个从 Access 数据库中的每日提要中获取记录并将记录添加到 sql server 的过程。

加载有时会失败,所以我尝试通过 SQL 服务器全局临时表添加,然后从该临时表中更快地删除/插入。

我有以下可在 TSQL 中运行的代码:

IF OBJECT_ID ( 'tempdb.dbo.####TempCountry' ) IS NOT NULL DROP TABLE ##TempCountry;  
SELECT * INTO ##TempCountry  FROM dbo.Country WHERE 1 = 2; 
INSERT INTO ##TempCountry (CountryCode, CountryName) VALUES ('AF','AFGHANISTAN') 
SELECT * FROM  ##TempCountry 

我已经使用 EntityFramework 连接将其转换为 ExecuteStoreCommand:

using (MyEntities _ent = new MyEntities ()) { 
  //Create a temp table 
  try { 
    _ent.ExecuteStoreCommand("IF OBJECT_ID ( 'tempdb.dbo.##TempCountry' ) IS NOT NULL DROP TABLE ##TempCountry"); 
    _ent.ExecuteStoreCommand("SELECT * INTO ##TempCountry FROM dbo.Country  WHERE 1 = 2"); 
    _ent.ExecuteStoreCommand("INSERT INTO ##TempCountry (CountryCode, CountryName, RegionCode) VALUES ('AF','AFGHANISTAN')"); 
  } catch (Exception ex) { 
    //Generic error  
    Console.writeline("  Unknown error inserting Country: {0} - {1} ", sCountryCode, ex.Message); 
  } 
} //EF 

当我点击最后一个 ExecuteStoreCommand 时,代码抛出一个 SqlException:“无效的对象名称‘##TempCountry’。”

但是当我执行“Select * from tempdb.dbo.sysobjects”时我可以看到该表

请您参考如下方法:

每个 ExecuteStoreCommand 将在不同的 session 中执行。一旦第一个命令执行完毕,该表将被删除。

来自 MSDN - CREATE TABLE (在临时表的备注部分下):

Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them.

一种解决方案是在一个 SQL 批处理中执行所有命令,而不是单独的命令。