views:

186

answers:

3

I'd like to be able to log all the SQL queries executed by the Entity Framework to log4net. What's the best way to do this?

+1  A: 

As far as I know, there is no simple solution to do it automatically. However you can easily get the SQL command for a query using the ToTraceString method :

var query = from p in context.Products
            where p.Price < 10.0
            select p;

Log(((ObjectQuery)query).ToTraceString());

To make it easier, you can create an extension to perform the cast to ObjectQuery :

public static string ToTraceString(this IQueryable query)
{
    ObjectQuery objectQuery = (ObjectQuery)query;
    if (objectQuery != null)
    {
        return objectQuery.ToTraceString();
    }
    return null;
}

Log(query.ToTraceString());
Thomas Levesque
That'll definitely do for finding the SQL for queries. What about for save/update/deletes run against the database?
Kevin Pang
No idea for save/update/delete... I'm not even sure it's possible to obtain the SQL query for those. But anyway, they should be pretty straightforward, since EF always generates updates/inserts/deletes based on the primary key
Thomas Levesque
There must be a way since the commercial product EFProfiler exists. To be honest, I'm a bit surprised at how difficult this is proving. I would think that being able to log your ORM queries would be one of the major selling points. Otherwise performance optimization becomes significantly more difficult.
Kevin Pang
+1  A: 

As Thomas wrote, there is no simple way (at least in VS2008), but I found a solution on MSDN and described an implementation on my blog. You only need to replace my file logging method with a call to log4net.

devio
A: 

You could use SQL Profiler as well.