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
2010-04-17 18:52:28
That'll definitely do for finding the SQL for queries. What about for save/update/deletes run against the database?
Kevin Pang
2010-04-17 19:01:18
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
2010-04-17 19:13:25
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
2010-04-19 16:53:40