【问题标题】:Why does EF Core 2.1 only add 1 index for 2 FKs?为什么 EF Core 2.1 只为 2 个 FK 添加 1 个索引?
【发布时间】:2019-11-02 09:58:30
【问题描述】:

我使用 SQL Server 2017 (v14.0.2027.2) 和 EF Core 2.1。

在此代码上添加迁移后:

public class TblTrack
{
    public long Id { get; set; }
    ...
}

public class TblProduct
{
    public long Id { get; set; }
    ...
}

public class TblProductItem
{
    [Key]
    [Required]
    public long ProductId { get; set; }

    [Key]
    [Required]
    public long TrackId { get; set; }

    // Navigation properties
    public TblProduct Product { get; set; }
    public TblTrack Track { get; set; }
}

Ef Core 只创建 TrackId 索引

migrationBuilder.CreateIndex(
name: "IX_tbl_ProductItems_TrackId",
table: "tbl_ProductItems",
column: "TrackId");

为什么为TrackId 创建了索引,而不为ProductId 创建了索引?

【问题讨论】:

  • 旁注:如果所涉及的两个键列都是 same 数据类型,则 FK/PK 关系最有效 - 您在两个表中的 PK 有 long,但 @987654326 @ 用于引用表中的 FK - 这应该是相同的(两者都 int,或两者都 long
  • 另外:这些关键字段的拼写:你有IDTrackID作为生成的密钥(其中ID全是大写),你有Id和@ 987654333@ 你又不一致了 - 一旦你用大写字母拼写,一个是混合大小写......尝试一致 - 要么拼写ID总是 - 要么始终使用Id - 但不要混合 ....

标签: c# sql-server entity-framework entity-framework-migrations ef-core-2.1


【解决方案1】:

为什么为 TrackId 创建索引而不为 ProductId 创建索引?

这实际上是 EF 非常聪明和正确的行为。 TblProductItem 的主键是 (ProductId,TrackId)。所以您已经有一个支持该外键的索引(因为 FK 列是该索引中的前导列)。只有尾部的 PK 列 (TrackId) 需要单独的索引来支持外键。

【讨论】:

  • 我不清楚为什么复合 PK 会这样工作。我的意思是为什么这样的PK一栏是“领先”而其他栏是“尾随”。您能否附上一些链接来解释它在数据库中的工作原理以及优点是什么?无论如何,我很感激你的回答。
猜你喜欢
  • 1970-01-01
  • 2017-01-11
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
  • 2021-08-22
  • 2018-11-30
相关资源
最近更新 更多