EFCore 迁移命令移除外键

Posted lludcmmcdull

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EFCore 迁移命令移除外键相关的知识,希望对你有一定的参考价值。

 

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

 

以上是关于EFCore 迁移命令移除外键的主要内容,如果未能解决你的问题,请参考以下文章

EFcore 数据迁移

EFCore之命令行工具

EFCore生产环境数据库升级方案

ef core数据迁移的一点小感悟

Efcore迁移

我可以避免在 EF Core 中使用迁移吗?