Skip to content

Conditional ForeignKeyIndexConvention #10855

@MykhayloKonopelskyy

Description

@MykhayloKonopelskyy

EF Core has ForeignKeyIndexConvention.
It conventionally adds indexes for FKs.
I would like to add indexes conditionally, not for all FKs.
For example, I would like to mark particular foreign key (for example with custom annotation), and to marked FKs ForeignKeyIndexConvention will not be applied.

Can I use something like this:

  1. Create my custom ForeignKeyIndexConvention, it can check whether FK is marked and applies or not applies ForeignKeyIndexConvention logic:
 public class CustomForeignKeyIndexConvention : ForeignKeyIndexConvention
    {
        public override InternalRelationshipBuilder Apply(InternalRelationshipBuilder relationshipBuilder)
        {
            var foreignKey = relationshipBuilder.Metadata;
            if (foreignKey.FindAnnotation("MyCustomAnnotationName") == null)
            {
                return base.Apply(relationshipBuilder);
            }

            return relationshipBuilder;
        }
....................................
  1. Create CustomCoreConventionSetBuilder which uses CustomForeignKeyIndexConvention instead of ForeignKeyIndexConvention.
public class CustomCoreConventionSetBuilder : CoreConventionSetBuilder, ICoreConventionSetBuilder
    {
        public CustomCoreConventionSetBuilder(
            CoreConventionSetBuilderDependencies dependencies)
            : base(
                  dependencies)
        {    }

        public override ConventionSet CreateConventionSet()
        {
            ...............................

            var foreignKeyIndexConvention = new CustomForeignKeyIndexConvention();

           ......................................
            
  1. Replace CoreConventionSetBuilder with my custom because I would like to use my custom ForeignKeyIndexConvention:
 builder.ReplaceService<ICoreConventionSetBuilder, CustomCoreConventionSetBuilder>();

Is it a right way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions