简体   繁体   中英

Entity Framework connection not recognizing Temp Table created

I've got a process that takes records from a daily feed in an Access database and adds the records to a sql server.

The load occationally fails, so I'm trying to add via a SQL server Global Temp Table and then a much quicker Delete/Insert from that temp table.

I've got the following code that works in 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

And I've translated this to ExecuteStoreCommand 's using an EntityFramework connection:

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

When I hit the final ExecuteStoreCommand , the code throws a SqlException: "Invalid object name '##TempCountry'."

But I can see the table when I execute a "Select * from tempdb.dbo.sysobjects"

Each ExecuteStoreCommand will execute on a different sessions. The table will be dropped as soon as the first command finishes executing.

From MSDN - CREATE TABLE (under the Remarks section, in Temporary Tables):

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

One solution is to execute all of the commands in one SQL batch, not separate commands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM