My question is related to this SO post, but instead of preventing I want to understand what's the convention of creating an index, as I can't find anything.
Given entities:
public class Entity1
{
public Guid Id {get;set;}
public string Name {get;set;}
public ICollection<Entity1Entity2Link> Links {get;set;}
}
public class Entity2
{
public Guid Id {get;set;}
public string Name {get;set;}
public ICollection<Entity1Entity2Link> Links {get;set;}
}
public class Entity1Entity2Link
{
public Guid Entity1Id {get;set;}
public Entity1 Entity1 {get;set;}
public Guid Entity2Id {get;set;}
public Entity2 Entity2 {get;set;}
}
And many to many relation setup:
modelBuilder
.Entity<Entity1Entity2Link>()
.HasKey(ofl => new
{
ofl.Entity1Id ,
ofl.Entity2Id
});
modelBuilder
.Entity<Entity1Entity2Link>()
.HasOne(ofl => ofl.Entity1)
.WithMany(e => e.Links)
.HasForeignKey(ofl => ofl.Entity1Id);
modelBuilder
.Entity<Entity1Entity2Link>()
.HasOne(ofl => ofl.Entity2)
.WithMany(e => e.Links)
.HasForeignKey(ofl => ofl.Entity2Id);
The resulting migration has index on Entity2Id
// create table etc...
migrationBuilder.CreateIndex(
name: "IX_Entity1Entity2Link_Entity2Id",
table: "Entity1Entity2Link",
column: "Entity2Id");
I'm looking to find what's the convention to create this index ? One convention I could find states:
EF Core will always create indexes for foreign key and alternate keys.
But then why I don't see another index on Entity1Id
column ?
Also I noticed I can swap index created on a column, by swapping column in composite key definition, e.g.
modelBuilder
.Entity<Entity1Entity2Link>()
.HasKey(ofl => new
{
ofl.Entity2Id,
ofl.Entity1Id
});
This will create an index on Entity1Id
column:
migrationBuilder.CreateIndex(
name: "IX_Entity1Entity2Link_Entity1Id",
table: "Entity1Entity2Link",
column: "Entity1Id");
I'm using EF Core 3.1.2.
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.2" />
See Question&Answers more detail:
os