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.
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:
- After you perform an Add-Migration...
- Modify your Migrations/yyyymmddhhmmss_Initial.cs file and...
- Completely empty the Up and Down methods
- Then continue to perform the Update-Database
- This gives you a clean starting point from which to make new database model changes (migrations) in the future.