All posts

Fix Migration Error in C# Entity Framework

Resolve Entity Framework migration errors in C# including snapshot conflicts, pending migrations, and database provider mismatches.

Entity Framework Migration Errors

EF Core migrations break when the model snapshot diverges from the database, when migrations conflict, or when the provider changes.

"The model has changed" Error

This means there are pending migrations:

dotnet ef migrations add FixModelChange
dotnet ef database update

Snapshot Conflict After Merge

When two branches add migrations, the snapshot file conflicts:

# After resolving merge conflicts in ModelSnapshot.cs
dotnet ef migrations remove  # Remove the broken migration
dotnet ef migrations add MergedChanges  # Regenerate

Common Errors and Fixes

"Cannot scaffold migration" — Model has errors:

// Missing navigation property configuration
public class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; } // Need to configure this
}

// In DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .HasOne(o => o.Customer)
        .WithMany(c => c.Orders)
        .HasForeignKey(o => o.CustomerId);
}

"Column already exists":

# If the database is ahead of migrations
dotnet ef database update 0  # Reset
dotnet ef database update     # Replay all

# Or mark a migration as applied without running it
dotnet ef migrations script --idempotent | # Review SQL first

Safe Migration Workflow

# 1. Create migration
dotnet ef migrations add AddUserEmail
# 2. Review the generated code
# 3. Test locally
dotnet ef database update
# 4. Verify rollback
dotnet ef database update PreviousMigration

Bugsly captures startup exceptions caused by migration failures, alerting your team immediately when a deployment breaks the database schema.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free