EFCore的导航属性在使用时非常方便,但是数据里生成的外键在现代编程理念里却不再像过去那样手欢迎,因为现代编程已经不再过分依赖数据库,特别是大型应用里面数据库通常是瓶颈所在,现在只是把数据库作为纯粹的数据存储角色,把其它东西都放在程序里处理,所以外键就不是那么必要,反而是数据操作时的麻烦(外键关系的存在,数据库必须维持特别是在操作数据时),这里查了一些文档和文章,实现如下。
[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) .Where(op => !(op is AddForeignKeyOperation)) .Where(op => !(op is DropForeignKeyOperation)) .ToList(); foreach (var operation in operations.OfType<CreateTableOperation>()) operation.ForeignKeys?.Clear(); return operations; } }
然后替换为自己的实现。
services.AddDbContext<MyDbContext>(options => { options.UseSqlServer(Default); options.ReplaceService<IMigrationsModelDiffer, MigrationsModelDifferWithoutForeignKey>(); });
在abpvenxt中可以如下操作,
在***.EntityFrameworkCore
项目中找到***DbContextFactory 的 CreateDbContext
方法中,使用
builder.ReplaceService();
即可