Capture Stored Procedure print output in .NET (Different model!)

后端 未结 4 975
余生分开走
余生分开走 2021-01-04 21:06

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 so

相关标签:
4条回答
  • 2021-01-04 21:37

    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​​​​​​

    0 讨论(0)
  • 2021-01-04 21:37

    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");
    
    
                }
    
    0 讨论(0)
  • 2021-01-04 21:39

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

    var sqlConn = (SqlConnection)Context.Connection.StoreConnection;
    
    0 讨论(0)
  • 2021-01-04 21:48

    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);
    
    0 讨论(0)
提交回复
热议问题