How I get the sql that Linq generates by debugging VS2013

Asked

Viewed 673 times

5

How do I get the sql that Linq generates by debugging VS2013? How do I do this?

I did it and it didn’t work

public static List<MontaArvoreAcao> CriarListaArvoreUn(string _uf, string _cidade, string _un)
        {
            RupturaEntities db = new RupturaEntities();

            var _listaUnidade = (
                                   from r in db.Ruptura
                                   join a in db.Apresentacao on r.Codigo_Apresentacao equals (a.Codigo_Apresentacao)
                                   join m in db.Motivo on r.IDMotivo equals (m.IDMotivo)
                                   where r.IDMotivo != 6
                                   group r by new { a.Unidade_Negocio, r.IDMotivo } into gr
                                   select new MontaArvoreAcao
                                   {
                                       IDMotivo = gr.Key.IDMotivo,
                                       Unidade_Negocio = gr.Key.Unidade_Negocio,
                                       Somatorio = gr.Count()
                                   }
                                 ).Distinct().ToList().OrderBy(r => r.IDMotivo);

            if (_un != "" && _un != null)
            {
                _listaUnidade = _listaUnidade.Where(u => u.Unidade_Negocio == _un).ToList().Distinct().OrderBy(o => o.Unidade_Negocio);
            }

            var query = _listaUnidade.ToString();**==> Aqui não deu certo**

            return _listaUnidade.ToList();
        }
  • I’m like the same doubt and really, the answer given below does not work! Unfortunately...

1 answer

2


When you select using Inline, the result will be of the type DbQuery<T>. The method .ToString() of that class is superscript to display the SQL command, then just call him:

var query = from foo in db.foo
            select foo;
var sqlGerado = query.ToString();
  • 1

    did not work. No sql generated came. That’s what came: System.Linq.Orderedenumerable`2[Rupture.Models.Montaarvoreacao,System.Int32]

  • 1

    Could you post relevant parts of the code so we can help you? This method I described has always worked for me, so I think your problem is a little more specific.

  • I made an edit of my method and the attempt to get the generated sql.

  • 3

    @pnet The reason is explained. Your query is executed when you call the .ToList() (I don’t know if the .Distinct() cause this effect, correct me if I am wrong). At this point your object ceases to be a DbQuery. If you want to see the SQL command generated by the query, store what is between parentheses in a variable, without calling the methods .Distinct().ToList().OrderBy(r => r.IDMotivo).

  • That’s right, thank you.

Browser other questions tagged

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