Search code examples
c#entity-frameworkentity-framework-4log4net

Entity Framework 4.0: How to log sql statements


I am using Entity Framework 4.0 in the application how to print log of sql statements .In EF 6 sampleEntities.Database.Log is working as below

readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public sampleEntities()
    : base("name=sampleEntities")
{
    this.Database.Log = s => log.Info("LINQSQLLOG : " + s);
}

Solution

  • You can do it as shown below.

    Method 1 :

    IQueryable myQuery = from x in yourEntities
                 where y.id = 45 
                 select y;
    
    var sql = ((System.Data.Objects.ObjectQuery)myQuery).ToTraceString();
    

    Method 2 :

    You can use Clutch.Diagnostics.EntityFramework API. It provides API for tracing EntityFramework sql commands.

    Nuget :

    PM > Install-Package Clutch.Diagnostics.EntityFramework
    

    API on Git : Clutch API

    Update : Logging and Tracing SQL Queries Clutch