Using a Separate Migrations Project
You may want to store your migrations in a different project than the one containing your DbContext
In good practice, you often have three projects:
- Entities Project which will contain all Entity (or Model) classes. These classes represent the database tables.
- DBContext Project help communicates between database and application.
- Application App Project uses DBContext.
Setup to using Migration tools on DBContext Project
- Implement default constructor in DBContext Project:
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
2. In Application Project -> startup.cs -> ConfigureServices
string dataPath =Configuration.GetConnectionString(“DefaultConnection”);
services.AddDbContext<ApplicationContext>(options =>options.UseMySql(dataPath,ServerVersion.AutoDetect(dataPath),b=>b.MigrationsAssembly(typeof(ApplicationContext).Assembly.FullName)));
Add Migration
In Visual Studio 2019:
open Package Manager Console -> in Default Project choose Context Project. In Solution Explorer, right-click on Application Project -> set as startup project.
add-migration Initial
update-database
In Visual Studio Code:
In the terminal, navigate into the Context Project folder
dotnet ef migrations add Initial — —startup-project “../ApplicationProject/ApplicationProject.csproj”
dotnet ef database update — — startup-project “../ApplicationProject/ApplicationProject.csproj”
“../ApplicationProject/ApplicationProject.csproj” : link to Application Project’ project file.