9

Basically, this question with a difference...

Is it possible to capture print output from a TSQL stored procedure in .NET, using the Entity Framework?

The solution in the other question doesn't work for me. It works with the connection type from System.Data.SqlClient but I'm using the one from System.Data.EntityClient which does not have an InfoMessage event. (Of course, I could just create an SQL connection based on the Entity connection settings, but prefer to do it directly.)

Community
  • 1
  • 1
Wim ten Brink
  • 25,901
  • 20
  • 83
  • 149

4 Answers4

12

Actually, it does, but since the EF is not SQL Server specific, you have to cast it:

var sqlConn = (SqlConnection)Context.Connection.StoreConnection;
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
9

Just to show people a complete working example from Craig's answer and Wim's response:

var entityConnection = (EntityConnection)Context.Connection;
var sqlConnection = (SqlConnection)entityConnection.StoreConnection;
sqlConnection.InfoMessage += (s,a) => Debug.WriteLine(a.Message);

​S​t​e​ve​​​​​​

Jogge
  • 1,654
  • 12
  • 36
samneric
  • 3,038
  • 2
  • 28
  • 31
1

This is what worked for me, samneric's example was helpful but not the exact syntax.

string message = Empty.string;

using (var context1 = new DatabaseEntities())
            {
                var conn =
                ((EntityConnection)
                    ((IObjectContextAdapter)context1).ObjectContext.Connection);

                var sqlConnection = (SqlConnection)conn.StoreConnection;

                sqlConnection.InfoMessage += (s, a) => message = a.Message;

              data = context1.storedProc("Parameter");


            }
Ryan Dooley
  • 224
  • 1
  • 3
  • 16
0

Based on the answer from @samneric, but with some modifications for EF Core we used this to allow debugging of a wayward stored procedure;

    DbConnection connection = Database.GetDbConnection();
    var sqlConnection = connection as SqlConnection;
    sqlConnection.InfoMessage += (s, a) => System.Diagnostics.Debug.WriteLine(a.Message);
Mr Moose
  • 5,946
  • 7
  • 34
  • 69