Starting with Visual Studio 2022 17.2 Preview 2, you can work with EF Core migrations straight from the IDE.
🎬Video: EF Core Migrations in Visual Studio 2022
git clone https://github.com/jeremylikness/MvpSummitTaskList
Open the IDE. Set MvpSummitTaskList
as the startup project and run it. This uses the in-memory service, so when you refresh the page you lose the state.
Right-click on the Connected Services
node and choose Add, then SQLite.
Give it the name todos.sqlite3
and use the local secrets file.
Follow the default prompts and it will install the dependencies.
Open the Program.cs and navigate to the service setup. Replace the line that configures ISummitTaskService
with this:
builder.Services.AddScoped<ISummitTaskService, DbSummitTaskService>();
builder.Services.AddScoped<ISummitTaskContextFactory, DefaultSummitContextFactory>();
builder.Services.AddDbContextFactory<SummitTaskContext>(opts =>
opts.UseSqlite("name=todos", b => b.MigrationsAssembly(nameof(MvpSummitTaskList))));
- Swaps to the database service
- Configures a custom factory (for this project, it is just a passthrough)
- Configures a factory to generate the SummitTaskContext
- Configures SQLite
- Uses the named connection string stored in secrets
- Sets the assembly for migrations to be written to
Finally, in preparation for migrations, add the EF Core design package to the MvpSummitTaskList
Blazor Server project.
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.1" />
The app is wired to use the database, but when you run it you receive an error because the database isn't configured.
Right click on the Connected Services
node and choose "Manage Connected Services." Click the ellipses next to SQLite and choose "Add migration."
It will take a moment to find the context. You can optionally rename the migration. When it's done, you should see a new migrations folder.
Using the same ellipses, choose the "Update database" option.
There is only one context, so you should just be able to click "Finish."
Run the application again. This time you should see it working. Add some tasks, mark a few complete, then restart to see the database in action.