Posts Tagged ‘Entity Framework’

Sample Provider for Entity Framework 4.0 is available

Today Entity Framework team released an update to Sample Provider for Entity Framework 4.0. The provider is intended to be an example for ADO.NET provider writers but can also be used and hacked upon by everyone interested in the inner workings of an EF provider.

The sample can be downloaded from MSDN Code Gallery. It is licensed under Microsoft Public License (Ms-PL). EFQuerySamples includes additional examples of configuring and using the sample provider.

Tags: , ,


Update to EFProviderWrappers is available

I’ve just posted a tiny update to EFProviderWrappers sample. It fixes the issue which was reported to me by several users, where NotSupportedException was being thrown during SaveChanges() from caching provider code.  

You can download updated bits from MSDN Code Gallery. If you find any other issues, please report them as comments here.

Tags: , ,


Improvements in generated SQL in EF v4.0

Kati from EntityFramework team has published a detailed post about improvments in generated SQL in Entity Framework v4.0. The improvements are really impressive and make generated SQL perform better and and look much closer to hand-written query code. The best thing is: almost all of the improvements are provider-agnostic, so you will see automatic improvement on queries running on 3rd-party providers. In some cases (LIKE optimization) you will need to use EF4-specific version of the provider.


Tags: ,

1 Comment

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: ,


Using EFProviderWrappers with precompiled views

One of the users has reported a problem with using EFProviderWrappers and precompiled views together.

When you pre-compile views, Entity Framework calculates a hash of metadata (which includes csdl,ssdl and msl information), stores it with the generated views and compares it later when metadata is loaded. When loaded metadata doesn’t match the hash stored in pre-compiled views, an exception is thrown. […]

[Read more on]

Tags: , , , ,

No Comments

Tracing and Caching for Entity Framework available on MSDN Code Gallery

We have just released a sample that shows how to extend Entity Framework in interesting ways by plugging into ADO.NET provider interface. The sample provides two extensions:

  • EFTracingProvider – which adds the ability to log all SQL commands that are executed (similar to LINQ to SQL’s DataContext.Log
  • EFCachingProvider – which adds transparent query results cache to EF

The sample comes with implementation of distributed cache which uses Velocity CTP 3 as well as an adapter for ASP.NET and simple in-memory cache implementation. […]

[Read more on]

Tags: , , , ,

No Comments

Entity Framework samples converted to Visual Basic

We have recently published Visual Basic versions of our MSDN Code Gallery samples for Entity Framework v3.5SP1.
The following translated samples are currently available in two languages (C# and VB) […]

[Read more on]

Tags: , , ,

No Comments

New posts on EF Design Blog

I’d like to turn your attention to two blog posts on EF Design Blog about exciting new features planned for Entity Framework […]

[Read more on]

Tags: , ,

No Comments