Using Linq to sql, how do I get the generated sql query?

Asked

Viewed 293 times

2

Hello.

If I have an example:

        var agendamento = _repository.First(a => a.iid == id
                                 && a.locIid == _usuario.LocalidadeContextoId
                                 && a.activeVersion == 0, "", true);

I can see the query SQL generated?

  • What is the database?

  • 1

    @Virgilionovic oracle bank

  • @itasouza are you using Entity Framework?

  • @Virgilionovic yes

2 answers

3

Using the Iqueryable, it is possible to obtain the SQL generated.

IQueryable<SuaClasse> query = _repository.First(a => a.iid == id
                             && a.locIid == _usuario.LocalidadeContextoId
                             && a.activeVersion == 0, "", true);

 var querySql = query.ToString();

1

Do the following in your context:

public DatabaseContext() : base("MeuContext")
    {
        //Trecho abaixo utilizado para ver as querys geradas pelo Entity
        #if DEBUG
        Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
        #endif
    }

That stretch System.Diagnostics.Debug.WriteLine(s) will cause all query generated appear in Output when you are debugging.

The answer that uses the IQueryable is also valid, but it is generally better to use it the way I have presented it here, because you want to check how your query was during the development and maintenance of the application to ensure that you are bringing the information correctly.

Of course this does not take away the validity of the option using IQueryble and depending on what you want it can be more useful.

Browser other questions tagged

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