Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging all Entity Framework queries in the debug window in DB-First Approach

I want to log the Entity Framework queries in my debug window. I could do that with the following line:

myContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

But how can I do that for all my queries in different functions and in different files?

Do I have to write this line everywhere?

Or is there a way to do this by writing a particular line of code to log every query at a single place.

As suggested, I have written the code in the constructor of the context but it's not working.

public partial class EkartEntities : DbContext
{
    public EkartEntities() : base("name=EkartEntities")
    {
        Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
    }
}

Am I doing something wrong?

Also, it is not duplicate of How to make EF log sql queries globally? as the post contains the answer of Code-First approach where we can simply modify our constructor.

like image 298
Suyash Gupta Avatar asked Nov 08 '22 02:11

Suyash Gupta


1 Answers

You can install global logger by adding the following class to the project containing your DbContext derived class:

class MyDbConfiguration : System.Data.Entity.DbConfiguration
{
    public MyDbConfiguration()
    {
        AddInterceptor(new System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter(
            s => System.Diagnostics.Debug.WriteLine(s)));
    }
}

The class represents the so called Code-based configuration and in this particular case is used to automatically register DatabaseLogFormatter with the specified Action<string> for all DbContext derived types and instances in the project that contains it.

like image 94
Ivan Stoev Avatar answered Nov 15 '22 07:11

Ivan Stoev