If you find yourself stuck because you need to use EF 6 features in an ASP.NET Core web app with Identity, don’t worry, it is easy!

Like many of you, I am trying to get all caught up with ASP.NET Core. It has some great features and I’ve been looking forward to using it. I finally have a new project to start so Core was my first choice.To expand on that a bit, I am using ASP.NET Core with the full .NET Framework. At this point, I don’t need to use .NET Core in cross platform scenarios.

It wasn’t long after I got started that I ran into what I thought was a big problem.Spoiler Alert: It wasn’t a big problem at all!

A new project created for ASP.NET Core (configured to use Individual Accounts for security) will be all loaded up with Entity Framework Core as well as Controllers and Views and Code to make all the authentication stuff work. This post isn’t about that. It was all working nicely. That is, until I needed Entity Framework Spatial Types with SQL Server. My website needs to calculate distance between two points, something that is surprisingly easy with the right tools. However, EF Core doesn’t yet support that! I’d needed EF 6 instead. Now, this is where I made my big mistake. I assumed that I couldn’t have EF 6 and EF Core in the same project so I removed all of the EF Core stuff. I began to set up EF 6 instead and ran into issues wiring things up with ASP.NET Core. To set up all of the Dependency Injection stuff and wire up services, you need code like this:

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

But it turns out that AddEntityFrameworkStores doesn’t exist in EF 6. This got me going on all kinds of research, trial and error. All for nothing.

You see, I was going about this all wrong.

Thanks to some help from Julie Lerman (Entity Framework Guru and fellow Microsoft MVP) and Diego Vega (from the EF team at Microsoft), I found out that I could in fact run EF 6 and EF Core in the same project! All I needed to do (after getting all of the EF Core nuget packages all loaded up again) was create 2 DbContexts! One with EF Core for the Identity stuff. And one with EF6 for my application logic (so I can use the spatial features including DbGeography). At first, I had a some namespace confusion because there are classes with the same names in EF 6 and Core. But that was easily resolved.

It’s great when the solution is so simple.