How to stop EF Core from indexing all foreign keys

If it is really necessary to avoid the usage of some foreign keys indices - as far as I know (currently) - in .Net Core, it is necessary to remove code that will set the indices in generated migration code file.

Another approach would be to implement a custom migration generator in combination with an attribute or maybe an extension method that will avoid the index creation. You could find more information in this answer for EF6: EF6 preventing not to create Index on Foreign Key. But I'm not sure if it will work in .Net Core too. The approach seems to be bit different, here is a MS doc article that should help.

But, I strongly advise against doing this! I'm against doing this, because you have to modify generated migration files and not because of not using indices for FKs. Like you mentioned in question's comments, in real world scenarios some cases need such approach.


For other people they are not really sure if they have to avoid the usage of indices on FKs and therefor they have to modify migration files:

Before you go that way, I would suggest to implement the application with indices on FKs and would check the performance and space usage. Therefor I would produce a lot test data. If it really results in performance and space usage issues on a test or QA stage, it's still possible to remove indices in migration files.

Because we already chat about EnsureCreated vs migrations here for completeness further information about EnsureCreated and migrations (even if you don't need it :-)):

  • MS doc about EnsureCreated() (It will not update your database if you have some model changes - migrations would do it)
  • interesting too (even if for EF7) EF7 EnsureCreated vs. Migrate Methods

EF Core has a configuration option to replace one of its services.

I found replacing IConventionSetBuilder to custom one would be a much cleaner approach.

https://giridharprakash.me/2020/02/12/entity-framework-core-override-conventions/