EFCore 迁移命令移除外键


 

继承 MigrationsModelDiffer,重载 GetDifferences 并移除 ForeignKeys

 

 1     [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "EF1001:Internal EF Core API usage.", Justification = "<挂起>")]
 2     public class MigrationsModelDifferWithoutForeignKey : MigrationsModelDiffer
 3     {
 4         public MigrationsModelDifferWithoutForeignKey
 5             ([NotNull] IRelationalTypeMappingSource typeMappingSource,
 6             [NotNull] IMigrationsAnnotationProvider migrationsAnnotations,
 7             [NotNull] IChangeDetector changeDetector,
 8             [NotNull] IUpdateAdapterFactory updateAdapterFactory,
 9             [NotNull] CommandBatchPreparerDependencies commandBatchPreparerDependencies)
10             : base(typeMappingSource, migrationsAnnotations, changeDetector, updateAdapterFactory, commandBatchPreparerDependencies)
11         {
12         }
13 
14         public override IReadOnlyList<MigrationOperation> GetDifferences(IModel source, IModel target)
15         {
16             var operations = base.GetDifferences(source, target)
17                 .Where(op => !(op is AddForeignKeyOperation))
18                 .Where(op => !(op is DropForeignKeyOperation))
19                 .ToList();
20 
21             foreach (var operation in operations.OfType<CreateTableOperation>())
22                 operation.ForeignKeys?.Clear();
23 
24             return operations;
25         }
26     }

 

 

使用时,替换服务即可:

  services.AddDbContext<MyDbContext>(options =>
  {
    options.UseSqlServer(Default);
    options.ReplaceService<IMigrationsModelDiffer, MigrationsModelDifferWithoutForeignKey>();
  });

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM