【问题标题】:Entity Framework connection not recognizing Temp Table created实体框架连接无法识别创建的临时表
【发布时间】:2011-09-19 18:39:14
【问题描述】:

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

加载偶尔会失败,因此我尝试通过 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”时我可以看到该表

【问题讨论】:

    标签: c# sql-server-2008 entity-framework-4 temp-tables


    【解决方案1】:

    每个ExecuteStoreCommand 将在不同的会话上执行。一旦第一个命令执行完毕,表就会被删除。

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

    当创建表的会话结束并且所有其他任务都停止引用它们时,将自动删除全局临时表。

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

    【讨论】:

    • 所以基本上,没有办法在循环中使用 ExecuteStoreCommand 和临时表来做任何工作......
    • @Christopher_G_Lewis - 如果你在一个ExecuteStoreCommand 中执行所有不同的 SQL 命令,我相信你会没事的。试试看。
    • 是的,但是这样做的想法是从 Access 数据库中读入并插入到 SQL 临时表中,对其进行验证并将其写入最终的 SQL 表中。
    • @Christopher_G_Lewis - 也许使用存储过程并传入table valued parameter 会是更好的解决方案。
    猜你喜欢
    • 2013-06-18
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多