Use DbContext in a Migration
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
## Ask a question
Is it possible to use a DbContext in a migration? Or inject services/dependencies into a migration?
Of course you can't generate a SQL script then, but when running migrations in C# it should work.
I need this for this case:
I need to alter the data and the data is currently calculated in C# at runtime. Now I'm save that calculation to the database for all current records.
### Include your code
Something like this:
```c#
public partial class MyMigration(MyDbContext myDbContext) : Migration // inject dbcontext
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn(
name: "calculatedValue",
schema: "dbo",
table: "MyTable",
type: "bigint",
nullable: true);
// Do some data migration when using the DbContext
// TODO myDbContext.MyTable.Where(x => x.Name ==) // Use DBContext
migrationBuilder.AddColumn(
name: "calculatedValue",
schema: "dbo",
table: "MyTable",
type: "bigint",
nullable: false);
}
}
```
#### Current work around:
1. Create a ICustomMigration
```c#
internal interface ICustomMigration
{
string Name { get; }
void ExecuteMigration();
}
internal class MyCustomMigration(MyDbContext dbContext, ILogger logger) : ICustomMigration { ... }
```
3. Add it to the DI
4. Run it after the EF Core migration
```c#
// Migrations
foreach (var dbContext in _dbContexts)
{
dbContext.Database.Migrate();
}
foreach (ICustomMigration customMigration in _customMigrations)
{
customMigration.ExecuteMigration();
}
```
But that has it downsides:
- I should check the `__EFMigrationsHistory` table
- The ordering with the EF Core migration is sometimes not correct, for example I like to have:
1. Add column (EF Core migration)
2. Do the data migration (Custom migration)
3. Make the column non-nullable. (EF Core migration)
- Rolling back needs also custom logic
### Include provider and version information
EF Core version: 8.0.6
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8
Operating system: Windows / Red Hat
IDE: Visual Studio 2022 17.9.6
Contributor guide
Assessment
This issue has not been assessed yet.