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

使用Git管理Entity Framework 6项目时迁移报错的解决咨询

EF6 多开发者Git协作下迁移冲突问题解决

问题场景

  • 开发者A新增模型后执行:
    add-migration model1
    update-database
    
  • 开发者B新增另一模型后执行:
    add-migration model2
    update-database
    
  • A推送代码,B拉取合并后执行update-database,出现错误:
    Specify the "-Verbose" flag to see the SQL statements applied to the target database.
    Applying explicit migration: [202304120237272_SupplierChatNoticeTo_add, 202304121001573_migration20230412].
    Applying explicit migration: 202304120237272_SupplierChatNoticeTo_add.
    Applying automatic migration: 202304120237271_SupplierChatNoticeTo_add_AutomaticMigration.
    System.Data.SqlClient.SqlException (0x80131904): An object named 'AbbrNameDicts' already exists in the database.
    ...
    Error Number: 2714, State: 6, Class: 16
    An object named 'Products' already exists in the database.
    
    核心问题:自动生成了不存在的202304120237271_SupplierChatNoticeTo_add_AutomaticMigration迁移,导致数据库对象重复创建报错。

原因分析

  1. 迁移历史不匹配:A、B各自本地执行update-database后,本地__MigrationHistory表记录了独立的迁移记录;Git合并后项目同时包含两个迁移文件,EF检测到模型与本地数据库历史不一致,触发自动迁移。
  2. 自动迁移未禁用:EF6默认可能开启自动迁移,当检测到模型变更未被显式迁移覆盖时,会自动生成临时迁移尝试修复,进而重复创建数据库对象。
  3. 迁移顺序逻辑混乱:合并后的迁移文件顺序被打乱,EF无法正确识别已执行的迁移操作,误判存在未覆盖的模型变更,触发自动迁移。

解决步骤

1. 禁用自动迁移

修改迁移配置类Configuration.cs,彻底关闭自动迁移,避免后续生成不必要的临时迁移:

internal sealed class Configuration : DbMigrationsConfiguration<YourDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false; // 禁用自动迁移
        AutomaticMigrationDataLossAllowed = false;
    }
    // 其他配置代码
}

2. 修复本地数据库与迁移文件的一致性

针对出现问题的开发者B:

  • 备份本地数据库(可选但推荐)。
  • 回退到合并前的最后一个有效迁移版本:
    update-database -TargetMigration:"model2"
    
  • 删除本地自动生成的临时迁移文件(如果存在)。
  • 重新执行合并后的所有迁移:
    update-database
    

3. 规范协作流程,避免冲突

  • 所有开发者创建新迁移前,必须先拉取最新代码,确保本地迁移文件同步:
    git pull
    
  • 拉取后先执行update-database同步本地数据库,再创建新迁移:
    update-database
    add-migration new_model_change
    update-database
    git add .
    git commit -m "Add migration for new model"
    git push
    
  • 合并迁移文件出现冲突时,手动编辑Up()和Down()方法,确保逻辑无重复创建对象的操作。

4. 极端情况:强制同步迁移历史

如果本地__MigrationHistory与项目迁移文件严重不一致:

  • 备份数据库后,清空__MigrationHistory表所有记录。
  • 生成全量迁移SQL脚本,检查无误后执行:
    update-database -Script -SourceMigration:0 -TargetMigration:Latest
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:07:47