实体框架在外键列上创建重复索引

时间:2015-09-20 23:38:28

标签: entity-framework foreign-keys

EF代码中最简单的2表定义 - 首先使用外键。

public class Blog {
    [Key]
    public int BlogId { get; set; }
    public string Name { get; set; }

    public virtual List<Post> Posts { get; set; }
}

public class Post {
    [Key, Column(Order = 0)]
    public int BlogId { get; set; }

    [Key, Column(Order = 1)]
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public virtual Blog Blog { get; set; }
}

生成

CREATE TABLE [dbo].[Blogs] (
    [BlogId] [int] NOT NULL IDENTITY,
    [Name] [nvarchar](max),
    CONSTRAINT [PK_dbo.Blogs] PRIMARY KEY ([BlogId])
)
CREATE TABLE [dbo].[Posts] (
    [BlogId] [int] NOT NULL,
    [PostId] [int] NOT NULL,
    [Title] [nvarchar](max),
    [Content] [nvarchar](max),
    CONSTRAINT [PK_dbo.Posts] PRIMARY KEY ([BlogId], [PostId])
)

CREATE INDEX [IX_BlogId] ON [dbo].[Posts]([BlogId])

ALTER TABLE [dbo].[Posts] 
   ADD CONSTRAINT [FK_dbo.Posts_dbo.Blogs_BlogId] 
   FOREIGN KEY ([BlogId]) REFERENCES [dbo].[Blogs] ([BlogId]) 
       ON DELETE CASCADE

BlogId是复合索引中用于维护主键的第一列,因此IX_BlogId是多余的,不会永远使用。

创造它有什么意义?

有类似的问题讨论索引外键列,但不是冗余索引: Entity Framework Indexing ALL foreign key columns

Entity Framework Code First Foreign Key adding Index as well

IMO,没有普遍的答案,即“它取决于”。它应该是一种禁用索引创建的简单方法。

0 个答案:

没有答案