Capture Tracesql query in LINQ c#

Asked

Viewed 121 times

1

I have an appointment in LINQ and I need to capture the generated sql, but I did not succeed. The conversion to Objectquery that I found does not work. What is missing?

var sqlConsulta = (from a in Sessao.Query<RequisitorioNaoLevantado>()
                  where (a.Codvara == codigoVara) &&
                      (string.IsNullOrEmpty(numeroProcesso) || 
                       a.AcaoOriginaria.Equals(numeroProcesso)) 
                 select a);

var sqlGerado = (ObjectQuery)sqlConsulta;
var commandSql = sqlGerado.ToTraceString();

For sqlConsulta.Tostring(), we have:

Nhibernate.Linq.Nhqueryable`1[Model...]

The line (Objectquery)sqlConsult, generates the exception:

"Cannont cast 'sqlConsulta' (which has an actual type of 'NHibernate.Linq.NhQueryable`1[Modelo.Entidades.Esparta.RequisitorioNaoLevantado]' to 'System.Data.Objects.ObjectQuery"

  • That’s what? Entity Framework?

  • The resources used are: Nhibernat + Fluentnhibernate + Linq;

1 answer

1


Has a reference to the Fluent Nhibernate in stackoverflow in English here

Write an Interceptor:

using NHibernate;
using System.Diagnostics;

public class SqlStatementInterceptor : EmptyInterceptor
{
    public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
    {
        Trace.WriteLine(sql.ToString());
        return sql;
    }
}

In your connection manager, connect your Interceptor like this:

protected virtual void Configure(FluentConfiguration config)
{
    config.ExposeConfiguration(x =>
                                   {
                                       x.SetInterceptor(new SqlStatementInterceptor());
                                   });
}
  • 1

    Thanks Ayrton, congratulations on the objectivity and clarity of the answer!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.