Entity Framework Core Override Conventions

Problem Statement: In our project, we use code first approach to generate migrations. I see one feature which I couldn’t control through Fluent API.

EF core is generating indexes on foreign keys. I see this as default behavior but I always like to have control in creating indexes.

Current Frameworks:

Asp.Net Core 2.2 API with EF Core.

Solution 1:

I can go and delete unwanted indexes after every migration is generated but this manual step might be missed one day, so I started looking for automating this.

Solution 2:

I found EF core configuration has given the option to replace one of its core services, so I tried to remove the Foreign Key Index convention.

public static IServiceCollection InitDatabaseContext(this IServiceCollection services, string connectionString)
services.AddDbContext<AppDbContext>(opts =>
opts.ReplaceService<IConventionSetBuilder, CustomSetBuilder>();
return services;
public class CustomSetBuilder : SqlServerConventionSetBuilder
public CustomSetBuilder(RelationalConventionSetBuilderDependencies dependencies, ISqlGenerationHelper sqlGenerationHelper) : base(dependencies, sqlGenerationHelper)
public override ConventionSet AddConventions(ConventionSet conventionSet)
var et = conventionSet.ForeignKeyAddedConventions.FirstOrDefault(f => f is ForeignKeyIndexConvention);
if (et != null)
return base.AddConventions(conventionSet);

I did generate a migration for my project with default conventions and then did generate migration after removing this convention. I am 100% convinced that this convention affected only default index creation for all foreign keys.

Note: Please test thoroughly before you add this to your project.

Have fun!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s