从 LINQ ExecuteMethodCall 中提取 SQL“打印”消息

Cyn*_*ulf 4 c# sql linq sql-server stored-procedures

我以一种相当简单的方式通过 LINQ 调用存储过程:

    [Function(Name = "dbo.add_second_override")]
    public int AddSecondOverride(
        [Parameter(DbType = "numeric(10)")] decimal account_id,
        [Parameter(DbType = "numeric(10)")] decimal security_id,
        [Parameter(DbType = "varchar(255)")] string reason,
        [Parameter(DbType = "numeric(10)")] decimal? order_id,
        [Parameter(DbType = "numeric(10)")] decimal current_user)
    {
        IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), new object[] { account_id, security_id, reason, order_id, current_user });

        if ((int)result.ReturnValue != 0)
        {
            string errorDescription = Sysmessages.FirstOrDefault(x => x.Error == (int)result.ReturnValue).Description;
            throw new Exception(errorDescription);
        }

        return (int)result.ReturnValue;
    }
Run Code Online (Sandbox Code Playgroud)

这工作正常,但如果存储过程中有 SQL 打印语句,我如何提取此信息?例如

create procedure dbo.add_second_override
(   
    @account_id numeric(10), 
    @security_id numeric(10), 
    @reason varchar(255) = null output,
    @order_id numeric(10) = null,
    @current_user numeric(10)               
) 
as
begin
    /* Do some other stuff */
    print 'This is a SQL message'
    return 0
end
Run Code Online (Sandbox Code Playgroud)

曾经有一种使用 SQLClient 检索此消息的方法,但我找不到与 LINQ 相关的任何内容。

请注意,我无法在存储过程中抛出异常而不是使用“打印”。它必须以某种方式获取打印语句。

Sea*_*sey 5

我没有找到任何特定于 Linq 的内容。但是从这个问题中排队

在 .NET 中捕获存储过程打印输出(不同的模型!)

如果您可以连接到 SqlConnection,您就可以对 InfoMessage 事件做出反应。

如果您使用 Entity Framework 和 DbContext - 您可以这样做。

SqlConnection conn = (SqlConnection)context.Database.Connection;
conn.Open();
conn.InfoMessage += (s, e) => Console.WriteLine(e.Message);
Run Code Online (Sandbox Code Playgroud)

正如我所说,我意识到这不是特定于 Linq 的方法 - 但至少您可以通过这样的方法实现最终目标。