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>();
  });

 

posted @ 2020-08-14 15:34  i没昵称  阅读(1078)  评论(7编辑  收藏  举报