EFCore 遷移命令移除外來鍵
阿新 • • 發佈:2020-08-14
繼承 MigrationsModelDiffer,過載 GetDifferences 並移除 ForeignKeys
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "EF1001:Internal EF Core API usage.", Justification = "<掛起>")] public class MigrationsModelDifferWithoutForeignKey : MigrationsModelDiffer { public MigrationsModelDifferWithoutForeignKey ([NotNull] IRelationalTypeMappingSource typeMappingSource, [NotNull] IMigrationsAnnotationProvider migrationsAnnotations, [NotNull] IChangeDetector changeDetector, [NotNull] IUpdateAdapterFactory updateAdapterFactory, [NotNull] CommandBatchPreparerDependencies commandBatchPreparerDependencies) :base(typeMappingSource, migrationsAnnotations, changeDetector, updateAdapterFactory, commandBatchPreparerDependencies) { } public override IReadOnlyList<MigrationOperation> GetDifferences(IModel source, IModel target) { var operations = base.GetDifferences(source, target);foreach (var operation in operations.OfType<CreateTableOperation>()) operation.ForeignKeys?.Clear(); return operations; } }
使用時,替換服務即可:
services.AddDbContext<MyDbContext>(options => { options.UseSqlServer(Default); options.ReplaceService<IMigrationsModelDiffer, MigrationsModelDifferWithoutForeignKey>(); });