Archive for April, 2010

Logging SQL statements in Entity Framework/Code First

Entity Framework/Code First feature released as part of Feature CTP 3 can work with any EF-enabled data provider.

In addition to regular providers which target databases, it is possible to use wrapping providers which can add interesting functionality, such as caching and tracing. In this post I’m going to explain how to use EFTracingProvider to produce diagnostic trace of all SQL commands executed by EF in Code First.

Setting up EFTracingConnection

In order to use the tracing provider, we need to create a wrapping DbConnection which adds logging every time the command has finished execution. The following helper will set up such connection. As you can see it can log commands to the console, log file or both. Plugging in additional logging mechanisms (such as System.Diagnostics, NLog or log4net) should be trivial.

private EFTracingConnection CreateTracingConnection()
    var connection = new EFTracingConnection
        ConnectionString = @"wrappedProvider=" + this.ProviderInvariantName + ";" + this.ConnectionString

    // set up an event which will be raised whenever command has finished executing
    connection.CommandFinished += (sender, e) =>
            if (this.LogToConsole)

            if (!string.IsNullOrEmpty(this.LogFileName))
                File.AppendAllText(this.LogFileName, e.ToTraceString() + Environment.NewLine + Environment.NewLine);
            // catch all exceptions so that we don't pass logging-related failures to user code

    return connection;

Object Context Factory

In order to efficiently manage tracing for the application we need to create a central factory class which will create ObjectContext instances for us. This is the place where we will create tracing provider connection and use it to instantiate ObjectContext.

Assuming our Object Context class is called MyContainer, the factory class will be called MyContainerFactory and will have a method called CreateContext, so the usage becomes:

MyContainerFactory factory = ...;

using (MyContainer context = factory.CreateContext())
    // use context normally

The factory will typically be be long-lived, created at the program startup and stored in a global variable or application state.

Having CreateTracingConnection(), we can now define our factory method by passing instance of the tracing connection to ContextBuilder<T>.Create():

/// <summary>
/// Creates instance of <see cref="MyContainer"/> with tracing enabled.
/// </summary>
/// <returns>Instance of <see cref="MyContainer"/>.</returns>
public MyContainer CreateContext()
    return contextBuilder.Create(this.CreateTracingConnection());

Simple, isn’t it?

Sample Project

I’ve created a tiny (100 lines of code) sample project which demonstrates this technique. Click here to download it

In the spirit of Code Only the project does not have any non-source artifacts (not even App.config file) and configures everything (model, mapping, tracing) through code:


Here is the output you get when running the application – as you can see all statements are logged to the console – log file is also created with similar output.



There is a known issue with this technique where creating databases is not supported on SqlClient provider. Other providers may or may not support this functionality depending on implementation. In general, because of that it is recommended to use unwrapped connections when using DDL APIs (CreateDatabase, DeleteDatabase, DatabaseExists()) as demonstrated in the sample.

Tags: ,


New version of EFProviderWrappers released

EFProviderWrappers sample for Entity Framework has been updated to support new features in EFv4 and Visual Studio 2010:

Changes in this release since 3.5SP1 version:

  1. Upgraded all projects to .NET 4.0 and retargetted assemblies to use .NET Framework 4 Client Profile
  2. Removed reflection-based code to invoke CreateCommandDefinition()
  3. Moved AspNetCache to a separate assembly (which depends on .NET Framework 4 Extended Profile)
  4. Added wrappers for new provider API surface of DbProviderManifest class:
    • bool SupportsEscapingLikeArgument(out char escapeCharacter)
    • string EscapeLikeArgument(string argument)
  5. Added wrappers for new provider API surface of DbProviderServices class:
    • void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection);
    • bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection);
    • void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection);
    • string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection);
  6. Wrappers now work in partial trust – check out AspNetCachingDemo
  7. Removed Velocity adapter and demo.
  8. Recreated sample models using edmx (instead of explicit csdl/ssdl/msl)
  9. Removed the need to explicitly install the database in SQL Server – instead using |DataDirectory| and mdf files local to the project.

The sample can be downloaded from MSDN Code Gallery.

Tags: , ,


Migrating from EF POCO Adapter to Entity Framework v4.0

Now that Visual Studio 2010 and .NET Framework 4.0 have been released, users of Entity Framework can use POCO objects with Entity Framework without the need for wrapper layers such as EFPocoAdapter. Since I know a number of people are using EFPocoAdapter in their production applications and it is not supported, I recommend they migrate to using native POCO support in EF v4.0 which is the supported way of using POCOs from now on.

This post will highlight the differences between EF and EFPOCOAdapter, which you must keep in mind when migrating your code base.

Read the rest of this entry »

Tags: ,


Blog migrated from

I’ve migrated my old blog at to the new domain.

In order not to duplicate content, but preserve the history I’ve created stub posts which link back to original content and recreated tag structure for easier navigation within the new site. All migrated posts are tagged as Migrated Post for easy identification.

No Comments