Simplest 2 table definition in EF code-first with foreign key.
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; }
}
Generates
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
is the 1st column in composite index to maintain primary key, hence IX_BlogId
is redundant and won’t be used ever.
What was the point creating it?
There were similar questions discussing indexing foreign key column, but not redundant indexes: Entity Framework Indexing ALL foreign key columns
Entity Framework Code First Foreign Key adding Index as well
IMO, there is no universal answer, i.e. "it depends". It should be an easy way to disable index creation.