我的问题与这个帖子 https://stackoverflow.com/questions/48645872/prevent-index-created-by-convention-on-many-to-many-table,但我不想阻止,而是想了解创建索引的约定是什么,因为我找不到任何东西。
给定实体:
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;}
}
以及多对多关系设置:
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);
生成的迁移在 Entity2Id 上有索引
// create table etc...
migrationBuilder.CreateIndex(
name: "IX_Entity1Entity2Link_Entity2Id",
table: "Entity1Entity2Link",
column: "Entity2Id");
我正在寻找创建此索引的约定是什么?我能找到的一项公约规定:
EF Core 将始终为外键和备用键创建索引。
但为什么我没有看到另一个索引Entity1Id
柱子 ?
我还注意到我可以通过交换复合键定义中的列来交换在列上创建的索引,例如
modelBuilder
.Entity<Entity1Entity2Link>()
.HasKey(ofl => new
{
ofl.Entity2Id,
ofl.Entity1Id
});
这将创建一个索引Entity1Id
column:
migrationBuilder.CreateIndex(
name: "IX_Entity1Entity2Link_Entity1Id",
table: "Entity1Entity2Link",
column: "Entity1Id");
我正在使用 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" />