Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

create non clustered index on primary key entity framework 6.0

I am aware of this, which states that it is not possible to create a primary key with non clustered index via code first. Is this still the case?

Ideally, I would like to specify via EntityTypeConfiguration, that my primary key (Guid) has a non-clustered index and there is another column (int) with a clustered index.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

AFAIK this is not possible with EntityTypeConfiguration. However you can do this with Code-First migrations. Working example:

public class Product
{
    public Guid Id
    { get; set; }

    public int Price
    { get; set; }
}

class AppDbContext : DbContext
{
    public DbSet<Product> Products
    { get; set; }
}

public partial class InitialCreate : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Products",
            c => new
                {
                    Id = c.Guid(nullable: false),
                    Price = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Id, clustered: false)
            .Index(t => t.Price, clustered: true);

    }

    public override void Down()
    {
        DropIndex("dbo.Products", new[] { "Price" });
        DropTable("dbo.Products");
    }
}

Result:

CREATE TABLE [dbo].[Products] (
    [Id]    UNIQUEIDENTIFIER NOT NULL,
    [Price] INT              NOT NULL,
    CONSTRAINT [PK_dbo.Products] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);

GO
CREATE CLUSTERED INDEX [IX_Price]
    ON [dbo].[Products]([Price] ASC);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...