create non clustered index on primary key entity framework 6.0

entity-framework entity-framework-6

Question

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.

1
4
5/23/2017 11:45:58 AM

Accepted Answer

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);
5
7/17/2015 5:40:04 PM

Popular Answer

You can also do this with your OnModelCreating method like so:

modelBuilder.Entity(entityTypeName)
    .HasKey(nameof(ClassName.Id))
    .ForSqlServerIsClustered(false);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow