Entity Framework 6 with ASP.NET 5

Introduction

From business application perspective being up to date with technology is a great challenge. Aging frameworks receive limited support and may become eventually abandoned. This may result in unresolved usability or security bugs. Older frameworks are usually less competitive than their newer versions in terms of costs and speed of development. They also attract less and less people willing to work for the company. This may become a huge problem especially for smaller projects where only one or two developers are required. Eventually effects are similar to having technical debt – important people leave project more often, overall knowledge degrades and costs of new features grow.

Obviously every rose has its thorn. Costs and risks of technological migrations may be overwhelming for some projects. Migrations have to be well planned ahead and the scope should be well defined. Big rewrites are best to be divided into several independent parts so that costs of failure is minimal.

Keeping in mind all best practices, migration of business application to ASP.NET 5 can be made a little easier if planned in separation to Entity Framework. Depending on current technical stack that project uses there may be different scenarios.

This article is intended to make some scenarios easier to implement. My first assumption is that there is a working implementation of project on ASP.NET MVC 5 and Entity Framework 6 Code First. Second – decision to migrate to ASP.NET 5 has begun. I am not able to cover all the possibilities but means presented below should be useful to other scenarios.

Project examples can be found on my GitHub account. You may also download them directly.

Migration blueprint

In the simplest form migration may fit into one line of code. This involves changes in Configure method in Startup class to setup IoC conatainer. Usually database context should be resolved once per web request. This way transactional behavior can be achieved and container is able to dispose context on response.

What about .config section?

You may be wondering how to use Entity Framework 6 with new ASP.NET 5 without relying on web.config or app.config file.
Usually there was a configuration section that Entity Framework 6 powershell commands handled while adding new provider or scaffolding new project. Typically looks like:

Starting from Entity Framework 6 above configuration can be specified in xml (app.config/web.config) of through code. Although config file takes precedence over code-based configuration ASP.NET 5 does not use config files at all. Code-based configuration is achieved by a creating a subclass of System.Data.Entity.Config.DbConfiguration and applying System.Data.Entity.DbConfigurationTypeAttribute to DbContext.

entityFramework/defaultConnectionFactory

The defaultConnectionFactory element sets the factory for connections. If this attribute is not set then the default value is SqlConnectionProvider. If, on the other hand, value is provided, given class will be used to create DbConnection with its CreateConnection method. If given factory has no default constructor then you must add parameters that are used to construct object.

entityFramework/providers
Specific provider is used, among others purposes, to create command objects specific for the database vendor. Some providers needs to register more than one dependency and some does not need them at all. By default SqlProviderServices is registered so having this entry is optional if using MsSql.

Entity Framework 6 recipes

SQL Server and SQL Server Express
This is the easiest case as there is no need for any configuration. Optionally code from previous part can be used to explicitly set connection factory and provider services.

SQL Server Express LocalDB
Using below code configures code first to utilize local db.

Setting connection factory to LocalDbConnectionFactory allows you to simplify connection string to database name.

Side note: Local database is stored in the user profile in %USERPROFILE%\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb folder. Browsing local databases is possible through SSMS. For automatic instance it is enough to put (localdb)/mssqllocaldb into server name input. If using named instance then pipe name must be found. The easiest way I found is to browse through errorXXX.log files located in mentioned folder. Line should look like this:
Server local connection provider is ready to accept connection on [ \\.\pipe\LOCALDB#FC424D5F\tsql\query ]
This connection can be pasted directly to SSMS as a server name.

SQL Server Managenemt Studio view on ExampleDatabase created with Entity Framework 6

Caution: Above scenario worked for me only for automatic migrations (I tried on beta8). Migrations generated by powershell, failed to create database. Entity Framework 6 throws FileNotFoundException while trying to find resources. I hope that this bug will be fixed until final release.

MySql
This very popular database needs some pre installations before working with Entity Framework or ADO.NET. Connector for MySql can be found on MySql site. After this initial step references to MySql.Data and MySql.Data.Entity have to be added to the project.

mysql references window

Configuration for DbContext:

Comprehensive documentation for connection strings for MySql can be found on www.connectionstrings.com. I used named pipe connection:

PostgreSql
Getting Npgsql connector to work with ASP.NET 5 was a little bit more tricky. Following documentation at Npgsql site answers only a few questions and is misleading in others. At first two nuget packages from nuget.org have to be installed:

  • Install-Package Npgsql -Version 3.0.3
  • Install-Package EntityFramework6.Npgsql -Version 3.0.3

In order to configure Npgsql following section has to be added to machine.config or app.config.

As this can not be achieved by our usual pattern new step have to be introduced. To be able to add DbProviderFactory in runtime we have to plug into dependency resolver of ADO.NET.

Summary

At first I thought that Entity Framework 6 should work without any problems on any configuration. It took me a lot more time to investigate all the problems that should be very simple so I hope that someone will find a value in my solutions. I have to say that it was much harder than I thought at the beginning.

Of course resolving Entity Framework 6 issues with ASP.NET 5 is only a beginning. There is still a steep learning curve ahead for the team which includes NodeJS, NuGet and other heavily utilized technologies. Hopefully ASP.NET team will be able to fill in some gaps in our knowledge by maintaining documentation and encouraging enthusiasts to create helpful community.

5 Comments

    1. @Matt K I’ve been struggling with the same bug but wasn’t as motivated to create an issue. Thanks – that will help many people !

  1. I have a IDbConnectionInterceptor configured for EF6, but I need to access the HttpContext in that interceptor. The interceptor is added in the CodeConfig, so I see no way to inject the HttpContext using the asp.net 5 platform services. Not since they removed the CallContextServiceLocator. Any suggestion how I would go and do this? 🙂

Leave a Reply