Is there a way to determine the current SQL Server session ID (@@SPID
) for an opened DbContext
, short of making a SQL query directly to the database?
If there is, is there any guarantee that the SQL Server session ID will remain the same until the DbContext
is released and its connection is released back to the Entity Framework connection pool? Something similar to this:
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<short>("SELECT @@SPID").FirstOrDefault();
}