Wednesday, May 15, 2013

Yet Another ORM Micro Benchmark, part 1/3, introduction

I’ve been experimenting with Entity Framework 5 Code First lately and one of my concerns was the performance on bare SELECTs as most of the time my applications just select the data.

In past, Entity Framework was never a fast mapper. In fact, my eariler experiments suggested that it is one of the most sluggish. As it turned out, there are quite a lot of factors a reliable benchmark has to consider regarding Entity Framework:

  1. EF relies on the metadata. A reliable test should not measure the time to create actual metadata but rather focus only on reading and materializing data.
  2. EF relies on “pregenerated” views, which are your actual queries. Similarily to metadata, view generation takes time so it should not be considered a factor.
  3. EF should supposedly be faster on .NET 4.5 while my earlier tests were performed on .NET 4.0
  4. It is important whether EF tracks changes to your entities or not

My fair tests should then consider all these factors and make sure that there is no single issue that could possibly spoil the results.

What other, similar benchmarks seem to omit is the fact that reading data behaves differently depending on the amount of data you actually read. There is a big difference in reading 1 entity vs reading 100 or 10000 entities when you compare different approaches.

I then decided to create a test environment with a database with two simple tables:

CREATE TABLE [dbo].[Child](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ID_PARENT] [int] NOT NULL,
    [ChildName] [nvarchar](150) NOT NULL,
 CONSTRAINT [PK_Child] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)
 
CREATE TABLE [dbo].[Parent](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ParentName] [nvarchar](150) NOT NULL,
 CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)
 
ALTER TABLE [dbo].[Child] WITH CHECK 
  ADD CONSTRAINT [FK_Child_Parent] FOREIGN KEY([ID_PARENT])
    REFERENCES [dbo].[Parent] ([ID])

As you can see there is Parent table and Child table and a foreign key between these two. Both tables of the database were filled with over 100k of random records.

Now introducing the contestants:

  1. (ADO) Bare ADO.NET SqlDataReader which materializes objects by fetching columns from the data reader and creating new instances manually
  2. (Linq2SQL) A Linq2SQL data context created from the database by sqlmetal.exe
  3. (EF5 Model First) A EF5 Object Context created from the database by using the designer
  4. (EF5 Code First) A EF5 DbContext created manually with entities created manually to match the database structure
  5. (nHibernate) A nHibernate model created manually to match the database structure

I am gonna implement tests for all contestants using C#+VS2012. Each test will implement a simple interface so that I can create and run them in a single environment:

public interface IPerformanceTest
{
    string Category { get; }
    string Name     { get; }
 
    void PerformTest( out DateTime StartedAt, out DateTime EndedAt );
}
The idea of my tests it not only just to select the data but perform selects to fetch TOP 1, 10, 100, 1000 and 10000 entities using Linq where applicable. The assumption is that no matter which tool you use, you expect a consistent query language, Linq.

Also, because selecting 1 or 10 records takes is too quick to measure reliably, my test runner will repeat tests 1000 times. Because of this, it will probably be possible to observe how different query mechanisms behave when the number of fetched rows changes.

As for the test environment – it is Win7x64 with SQL Server 2012, 8GB RAM and 4 core i7 processor. Tests will be performed on .NET 4.5 in Release mode, the runner is executed from the OS shell directly rather than from VS2012.

In the next post I will show how all tests are implemented. Then, in the 3rd post we will analyze and comment the results.

Monday, May 13, 2013

Viewing Generated Proxy Code for Entity Framework 5 Code First

There is an old post by David DeWinter which shows how to see the proxy code generated by EF. The information is a little bit outdated or at least, there is no information on how to do the same for Code First approach.

The problem stems from the fact that David uses the CreateProxyTypes method which is not available on the DbContext class.

There are two possible approaches to get the same result (an assembly containing all your proxy types) for Code First’s DbContext.

An easiest approach is to switch the AssemblyBuilderAccess strategy just before you access any of your data. Then execute a linq statement on one of your DbSets and the proxy will automatically be created and thus – it can be persisted.

// this assumes that ctx is of type DbContext
ctx = new YourDbContext();
 
// switch the strategy to allow the assembly to be persisted
Type entityProxyFactoryType = Type.GetType(
     "System.Data.Objects.Internal.EntityProxyFactory, " + 
     typeof( ObjectContext ).Assembly.FullName );
 
const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Static;
entityProxyFactoryType.GetField( "s_ProxyAssemblyBuilderAccess", bindingFlags )
     .SetValue( null, AssemblyBuilderAccess.RunAndSave );
 
// this forces the proxy to be created
foreach ( var entity in ctx.OneOfYourDbSets )
{
}
 
var moduleBuilders = (IDictionary<Assembly, ModuleBuilder>)
    entityProxyFactoryType.GetField( "s_ModuleBuilders", bindingFlags ).GetValue( null );
 
var pocoProxyModule = moduleBuilders[typeof( YourDbContext ).Assembly];
var pocoProxyAssembly = (AssemblyBuilder)pocoProxyModule.Assembly;
 
pocoProxyAssembly.Save( "EntityProxyModule.dll" );

This method has one disadvantage – the persisted assembly doesn’t contain all possible proxies but rather – only these proxies that have been created so far (OneOfYourDbSets in the above snippet).

A difficult approach is to get deeply under the hood of the DbContext and fix David’s code to still work for this scenario:

var ctx = new YourDbContext(); 
 
Type entityProxyFactoryType = Type.GetType(
    "System.Data.Objects.Internal.EntityProxyFactory, " + 
    typeof( ObjectContext ).Assembly.FullName );
 
const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Static;
entityProxyFactoryType.GetField( "s_ProxyAssemblyBuilderAccess", bindingFlags )
    .SetValue( null, AssemblyBuilderAccess.RunAndSave );
 
// dig deeply to the internal ObjectContext in the DbContext
var changeTracker = ctx.ChangeTracker;
object _internalContext = changeTracker.GetType().InvokeMember( "_internalContext", 
    BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, changeTracker , null );
object _objectContext = _internalContext.GetType().InvokeMember( "ObjectContext", 
    BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, _internalContext, null );
 
ObjectContext objectContext = _objectContext as ObjectContext;
 
objectContext.CreateProxyTypes( Assembly.GetExecutingAssembly().GetTypes() );
 
var moduleBuilders = (IDictionary<Assembly, ModuleBuilder>)
    entityProxyFactoryType.GetField( "s_ModuleBuilders", bindingFlags ).GetValue( null );
 
var pocoProxyModule = moduleBuilders[typeof( YourDbContext ).Assembly];
var pocoProxyAssembly = (AssemblyBuilder)pocoProxyModule.Assembly;
 
pocoProxyAssembly.Save( "EntityProxyModule.dll" );

In both cases, the generated assembly can be inspected with any IlSpy-like tool.

Monday, May 6, 2013

Entity Framework 5 Code First Multi-Tenancy with Migrations

The Entity Framework 5 Code First Migrations mechanism works great, however there is a small issue regarding multi tenant applications where the same DbContext is used to connect to multiple databases with the same schema.

To be able to address multiple databases with the same schema, you could have two constructors:

public class MyDbContext : DbContext
{
   public MyDbContext() : 
      base( defaultconnectionstring )
   {
   }
 
   public MyDbContext( string ConnectionString ) : 
      base( ConnectionString )
   {
   }
}

or have a single, parameterless constructor but set the connection string after a context has been created. In both cases, the default parameterless constructor will always somehow point to a concrete, default database.

This raises following problem - the MigrateDatabaseToLatestVersion initializer creates your context using the default parameterless dbcontext constructor. It will migrate the database but only the default one! It seems that people report this issue.

To fix this, we need a modified database initializer. The initializer should migrate the current database rather than the default one. It means that the initializer should get the connection string from the current context somehow. Luckily, this is possible:

// an example code first data context
public class MasterDetailContext : DbContext
{
    public DbSet<Detail> Detail { get; set; }
    public DbSet<Master> Master { get; set; }
 
    // this one is used by DbMigrator but the client code will not use it
    public MasterDetailContext()
    {
        Database.Initialize( false );
    }
 
    // rather - the client code will use this one
    public MasterDetailContext( string ConnectionString ) : base( ConnectionString )
    {
        Database.SetInitializer( new CustomInitializer() );
        Database.Initialize( false );
    }
 
    protected override void  OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}
 
public class CustomInitializer : 
   IDatabaseInitializer<MasterDetailContext>
{
 
    #region IDatabaseInitializer<MasterDetailContext> Members
 
    // fix the problem with MigrateDatabaseToLatestVersion 
    // by copying the connection string FROM the actual context!
    public void InitializeDatabase( MasterDetailContext context )
    {            
        Configuration cfg = new Configuration(); // migration configuration class
        cfg.TargetDatabase = 
           new DbConnectionInfo( 
              context.Database.Connection.ConnectionString, 
              "System.Data.SqlClient" );
 
        DbMigrator dbMigrator = new DbMigrator( cfg );
        // this will call the parameterless constructor of the datacontext
        // but the connection string from above will be then set on in
        dbMigrator.Update();             
    }
 
    #endregion
}

The client code is now:

// Connect to two different schemas using the same context
// Use sql profier to see how both databases are migrated
using ( MasterDetailContext ctx = 
   new MasterDetailContext( @"Database=Database01;Server=.\SQL2012;Integrated Security=true" ) )
{
}
 
using ( MasterDetailContext ctx = 
   new MasterDetailContext( @"Database=Database02;Server=.\SQL2012;Integrated Security=true" ) )
{
}

Compare our new custom initializer with the existing MigrateDatabaseToLatestVersion initializer:

// The builtin initializer class
public class MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration> : 
   IDatabaseInitializer<TContext> 
      where TContext : DbContext 
      where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()
{
   private readonly DbMigrationsConfiguration _config;
 
   public MigrateDatabaseToLatestVersion()
   {
      // creates the migrations configuration instance
      this._config = Activator.CreateInstance<TMigrationsConfiguration>();
   }
 
   public void InitializeDatabase(TContext context)
   {
      // migrates the default database (doesn't use context!)
      DbMigrator dbMigrator = new DbMigrator(this._config);
      dbMigrator.Update();
   }   
}

Differences are obvious.

The built in initializer uses reflection to create the instance of the migrations configurator and asks DbMigrator to perform the update but it doesn’t ask it for the connection to the current database! Instead, the configurator by itself creates a new instance of the DbContext using the default parameterless constructor. On the other hand, our custom initializer uses the information on the context to set the configurator’s TargetDatabase to point to a current database.

This way, multiple databases can be migrated independently.

Wednesday, March 27, 2013

Annotation-based Documentation Provider for APIExplorer

The APIExplorer is a nice way to automatically build a docs page for your WebAPI RESTful services. The documentation is created using reflection and then the IDocumentationProvider tries to find the textual information about your methods and method parameters.

The problem is that the reference implementation shows how the docs could be retrieved from the XML documentation generated during the compilation of a service. If this is not an option for you, you could use this simple provider which uses System.ComponentModel.DataAnnotations.Display attributes for method decoration:

public class AttributeDocumentationProvider : IDocumentationProvider
 {
     #region IDocumentationProvider Members
 
     public string GetDocumentation( HttpParameterDescriptor parameterDescriptor )
     {
         ReflectedHttpParameterDescriptor reflectedParameterDescriptor = 
             parameterDescriptor as ReflectedHttpParameterDescriptor;
         if ( reflectedParameterDescriptor != null )
         {
             var display = reflectedParameterDescriptor.ParameterInfo
                 .GetCustomAttributes( typeof( DisplayAttribute ), false )
                 .OfType<DisplayAttribute>().FirstOrDefault();
             if ( display != null )
                 return display.Description;
             else
                 return reflectedParameterDescriptor.ParameterInfo.Name;
         }
 
         return string.Empty;
     }
 
     public string GetDocumentation( HttpActionDescriptor actionDescriptor )
     {
         ReflectedHttpActionDescriptor reflectedActionDescriptor = 
             actionDescriptor as ReflectedHttpActionDescriptor;
         if ( reflectedActionDescriptor != null )
         {
             var display = reflectedActionDescriptor.MethodInfo
                 .GetCustomAttributes( typeof( DisplayAttribute ), false )
                 .OfType<DisplayAttribute>().FirstOrDefault();
             if ( display != null )
                 return display.Description;
             else
                 return reflectedActionDescriptor.MethodInfo.Name;
         }
 
         return string.Empty;
     }
 
     #endregion
 }

This way the WebAPI controller could be documented as follows:

public class MyWebAPIController : ApiController
{
    /// <summary>
    /// POST/Create a new Foo
    /// </summary>
    [Display( Description="Create a new instance of Foo")]
    public HttpResponseMessage PostFoo( 
        [Display( Description="Name of the newly created Foo")]
        string fooName 
        )
    {
       ...

An advantage of this approach is that the docs are part of the assembly metadata and there is no need for external XML documentation files.