Friday, April 21, 2017

Entity Framework Core: Migrate and update a repository in class library

As of April 2017, Entity Framework Core (and Visual Studio 2017) does not support having your database repository in a separate class library.  Here are the steps I followed in order to work around this.  This was done successfully even with multiple repositories (i.e. more than one DbContext).

Hope this can help others as it took me awhile to get it right.  I did these steps for more than one DbContext and database so I'm sure this works as of the time I wrote this post.

Here is what I did to get things working nicely:

Added nuget packages:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools

Added Program.cs to the class library project:
public class Program
{
 public static void Main(string[] args)
 {

 }

 public class xxxxContextFactory : IDbContextFactory<xxxxDbContext>
 {
  public xxxxDbContext Create(DbContextFactoryOptions options)
  {
   //
   // this is only used for data migrations and db updates; the connection
   // string is not used for production
   //

   var optionsBuilder = new DbContextOptionsBuilder<xxxxDbContext>();
   optionsBuilder.UseSqlServer("Server=.;Database=xxxxDatabase;Trusted_Connection=True;MultipleActiveResultSets=true");

   return new xxxxDbContext(optionsBuilder.Options);
  }
 }
}


Added property group to .csproj:
<PropertyGroup>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>

Set xxxxRepositoryModel as startup project.

Set the Package Manager Console "Default project" to your repository project.

Open Package Manager Console and then:
   PM> cd xxxxRepositoryModel
   PM> Add-Migration Initial -context xxxxDbContext
   PM> Update-Database -c xxxxDbContext

Note: If this is a brand new repository based on an EXISTING database and you have done the Package Manager command, Scaffold-DbContext, then you will need to:

  1. After you perform an Add-Migration...
  2. Modify your Migrations/yyyymmddhhmmss_Initial.cs file and...
  3. Completely empty the Up and Down methods
  4. Then continue to perform the Update-Database
  5. This gives you a clean starting point from which to make new database model changes (migrations) in the future.


No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...