Porting to Entity Framework Core

I’ve used the newer Entity Framework Core on a couple projects just to give it a test drive in the v1.0 era. It felt very similar to Entity Framework 6. I figured since it seemed so similar, porting wouldn’t be too difficult. So I bit the bullet and finally decided to port an application that uses Entity Framework 6 over to Entity Framework Core 2.0. Here is a bit of an experience report on porting to Entity Framework Core.

Side by Side

In theory, you should be able to run EF 6 along side EF Core. They are completely different packages, assemblies and namespaces.

However in practice, that wasn’t possible in my situation.

MySql.Data

This project in particular that I was porting was using MySQL. The official provider to use with EF6 is MySql.Data.Entity. This package has a dependency on the ADO.NET driver MySql.Data.

EFCore has an official provider, MySql.Data.EntityFrameworkCore. It also has a dependency on MySql.Data, but a newer version. A wonderful diamond dependency. Full roadblock.

Porting

I ended up removing all of the EF6 packages and references and installed the latest EF Core package and MySQL provider. Here are some of the changes that I needed to make.

DbContext

My only significant change was adding a OnConfiguring override to specify which provider to use and the connection. The extension method UseMySql is from the MySql provider, which is being passed the connection.

https://gist.github.com/dcomartin/96e88250759c537084012a5ec1bbda1d

This is no longer available and you must now use the FromSql method to perform raw SQL queries. FromSql is available on all the DbSet<T> in your DbContext

https://gist.github.com/dcomartin/f70b54ff8f320e73a9e2c7d9926bc46b

Using statements were more of a pain then anything. Really a matter of removing any using statements to System.Data.Entity and replacing with relevant Microsoft.EntityFrameworkCore

Composite Key

You can no longer use data annotations to declare composite keys. This must be done through the fluent API.

https://gist.github.com/dcomartin/5e8f1e9c10b65cb946d18a8fc946d074

As of EF Core 2, lazy loading is not supported. Luckily I’ve never been a fan of lazy loading and generally find it causes more harm then good. If you are using lazy loading, there’s a package EntityFramework.LazyLoading that enables the ability with some minor changes to your DbContex

To Be Continued…

This was my first pass at a small project that was using EF6 and the issues that came up while porting to Entity Framework Core. I will keep this post updated when I discover more situations while porting other applications.

Have you ported to EF Core? Please share your insights in comments or on Twitter.

Follow @codeopinion

Like what you read? Give Derek Comartin a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.