title: How can I collect the current SQL Server Session ID from an Entity Framework DbContext?
body: <p>Is there a way to determine the current SQL Server session ID (<code>@@SPID</code>) for an opened <code>DbContext</code>, short of making a SQL query directly to the database?  </p>
  
  <p>If there is, is there any guarantee that the SQL Server session ID will remain the same until the <code>DbContext</code> is released and its connection is released back to the Entity Framework connection pool? Something similar to this:</p>
  
  <pre><code>using (MyEntities db = new MyEntities()) {
  
      // the following 3 pieces of code are not existing properties and will result in compilation errors
      // I'm just looking for something similar to the following 3 lines
      db.CurrentSessionId; //error
      db.Database.CurrentSessionId; //error
      ((IObjectContextAdapter)db).ObjectContext.Connection.CurrentSessionId; //error
  
      // the following code will work, but will this session id be the same until the original DbContext is disposed?
      // is there any chance that a db.Database.SqlQuery call will spin off it's own connection from the pool?
      short spid = db.Database.SqlQuery&lt;short&gt;("SELECT @@SPID").FirstOrDefault();
  }
  </code></pre>