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

Asked

Viewed 1,827 times

6

With the use of 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 Entity Framework right in the Visual Studio, so that you can debug and have greater control over what is being generated?

1 answer

2


As far as I know there are two ways:

1) Creates the expression lambda expression (Linq) in return Iqueryable and another variable SQlExecutar perform a Tolist(). In the variable with return Iqueryable has the SQL generated.

In this code shown, when passing the instruction SQL.ToList() 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();        
}

inserir a descrição da imagem aqui

One way to visualize this is also with Breakpoint with F11 in the window Intellitrace see the output, Observer:

inserir a descrição da imagem aqui

2) In the version EPH 6+, there is a Action responsible for this by having a way out of all the information from connection and the Sqls. The Database.Log redeems such information with the encoding below. I create a Function that has a type parameter String that receives the data and prints on 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);
}

inserir a descrição da imagem aqui

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 visualize Insert, Delete, Update and Select very clearly.

Browser other questions tagged

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