You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET Core 2.0中实现EF Core模型变更的编程式迁移?

Hey there! I’ve worked with EF Core 2.0 quite a bit, so let’s walk through how to handle model changes (adding/modifying/deleting columns or even tables) with programmatic migrations—since EF Core doesn’t have EF6’s automatic migration feature, we’ve got a few reliable approaches here.

1. Auto-Apply Migrations on App Startup

This is the most common approach, ensuring your database stays in sync with your model as soon as the app boots up.

First, make sure your DbContext is registered in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<YourDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
    // Other service registrations...
}

Then, inject your DbContext into the Configure method and call Migrate():

public void Configure(IApplicationBuilder app, IHostingEnvironment env, YourDbContext dbContext)
{
    // Configure middleware (routing, logging, etc.) first...

    // Apply all pending migrations
    dbContext.Database.Migrate();
}

The Migrate() method automatically applies any unexecuted migrations to your database—this covers all model changes you’ve captured via migration files (created with Add-Migration or dotnet ef migrations add).

2. Trigger Migrations Manually (e.g., via API Endpoint)

If you don’t want migrations running automatically on startup, create a dedicated API endpoint to trigger them on demand.

Here’s a sample controller:

[ApiController]
[Route("api/migrations")]
public class MigrationsController : ControllerBase
{
    private readonly YourDbContext _dbContext;

    public MigrationsController(YourDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpPost("apply")]
    public async Task<IActionResult> ApplyPendingMigrations()
    {
        try
        {
            await _dbContext.Database.MigrateAsync();
            var appliedMigrations = await _dbContext.Database.GetAppliedMigrationsAsync();
            return Ok($"Successfully applied {appliedMigrations.Count()} migrations.");
        }
        catch (Exception ex)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, 
                $"Migration failed: {ex.Message}");
        }
    }
}

Now you can send a POST request to /api/migrations/apply whenever you need to sync the database with your model changes.

3. Check for Pending Migrations First

If you want to avoid unnecessary migration runs (or add logging/alerting), check for pending migrations before executing them:

public async Task CheckAndApplyMigrations(YourDbContext dbContext)
{
    var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync();
    
    if (pendingMigrations.Any())
    {
        await dbContext.Database.MigrateAsync();
        // Log the applied migrations:
        foreach (var migration in pendingMigrations)
        {
            // _logger.LogInformation($"Applied migration: {migration}");
        }
    }
    else
    {
        // _logger.LogInformation("No pending migrations to apply.");
    }
}

Call this method from startup, a background job, or your API endpoint—it gives you more control over when and how migrations are applied.

Key Notes to Remember
  • Always create migration files first: Before using any of these methods, generate migration code for your model changes using:
    • Package Manager Console: Add-Migration YourMigrationName
    • Command Line: dotnet ef migrations add YourMigrationName
  • Production caution: Auto-migrations are convenient for development, but in production, consider generating SQL scripts first with Script-Migration to validate changes before applying them—this helps avoid accidental data loss or schema errors.
  • Database permissions: Ensure your app’s database account has sufficient privileges to modify the schema (e.g., ALTER TABLE, CREATE TABLE permissions).

内容的提问来源于stack exchange,提问作者Illep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:47:29