How to know which SQL is generated by the ORM Entity Framework?

4

With the use of the ORM , and the practice employed we forget that they generate SQLs and return Objetos (vice versa).

How can I find out at runtime the SQL generated by the Entity Framework directly in Visual Studio , so you can debug and have more control over what is being generated?

    
asked by anonymous 14.06.2014 / 17:48

1 answer

1

As far as I know, there are two ways:

1) Creates the expression lambda expression ( Linq ) with return IQueryable and in another variable SQlExecutar run a ToList () . In the return variable IQueryable has the < in> SQL generated.

In this code, when you pass the SQL.ToList() statement above the variable SQL will show the SELECT generated:

using (GenericsEntities db = new GenericsEntities())
{
    //Quando a variável "SQL" der um ToList() ela mostrado a "SELECT"
    IQueryable<Tipos> SQL = db.Tipos.AsQueryable();    
    IList<Tipos> SQLExecutar = SQL.ToList();        
}

OnewaytovisualizethisisalsowithBreakpointwithF11intheIntelliTracewindowtoviewoutput,observer:

2) In the EF 6 + version, there is a #

  • strong>. Database.Log retrieves such information with the encoding just below. I created a function that has a parameter of type String that receives the data and prints to the console screen.

    using (GenericsEntities db = new GenericsEntities())
    {
        db.Database.Log = StrRestult => fs(StrRestult); 
        IQueryable<Tipos> SQL = db.Tipos.AsQueryable();
        IList<Tipos> SQLExecutar = SQL.ToList();
    }
    //função que irá imprimir na tela (console) tudo o que 
    //aconteceu nas instruções de conexão e SQLs geradas
    private static void fs(string StrRestult)
    {
        System.Console.WriteLine(StrRestult);
    }
    

    It is very useful as a way to debug and visualize how it works internally.

    The second option is the most effective because I can also see Insert , Delete , Update and Select quite clearly.

        
  • 14.06.2014 / 17:48