The Secret to Running EF Core 2.0 Migrations from a NET Core or NET Standard Class Library

I have had two people that watched my Pluralsight EF Core Getting Started course (which will soon be joined by an EF Core 2: Getting Started course) ask the same question, which mystified me at first.


The were running migrations commands which caused the project to compile, but the commands did not do anything. For example, add-migration didn’t add a migration file. get-dbcontext did not return any information. The most curious part was there was no error message! I was able to duplicate the problem.


With EF6 it was possible to use migrations from a class library with no exe project in sight. EF Core migrations can run from a .NET Framework or .NET Core project but not .NET Standard. It needs a runtime.


We already knew about the multi-targetting fix which solved an error when you try to run migrations from a .NET Standard library. But even with that fix in place, we were getting the mysterious nothingness.


The answer to the question was buried in a GitHub issue and in comments for the Migrations document in the EF Core docs. This same solution solved a problem I was having when trying to use migrations in a UWP app (again, not .NET Core or .NET Framework) that used a separate class library to host its DbContext.


I’m writing this blog post to surface the solution until it is resolved.


The solution that we used with EF Core 1.0 in order to run migrations from a .NET Standard library was to multi-target for .Net Standard (so you can use the library in a few places) and .NET Core (so you can run migrations).


That means replacing



      netstandard20

with



       netcoreapp2.0;netstandard2.0

Notice that the attribute name is now plural and there is a semi-colon between the two SDKs.


But there’s one more secret which is not in the documentation.


For .NET Standard 2.0 (and EF Core 2.0), you also need to add the following to csproj.


    
true

Now with the DbContext project set as the startup and ensuring that the package manager console (or command line) are pointing to the same project, your migration commands will work.


Thanks to Christopher Moffat who found the solution in the GitHub issues and shared it in the comments on the EF Core Package Manager Console Tools document.

 •  0 comments  •  flag
Share on Twitter
Published on January 04, 2018 18:01
No comments have been added yet.


Julia Lerman's Blog

Julia Lerman
Julia Lerman isn't a Goodreads Author (yet), but they do have a blog, so here are some recent posts imported from their feed.
Follow Julia Lerman's blog with rss.