Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non Clustered Primary Key Entity Framework Code First

In Entity Framework Code First approach, can we define the Primary Key as non-clustered index and a combination of few other fields as clustered index.

Thanks

like image 244
Satyajit Avatar asked Jun 16 '16 09:06

Satyajit


People also ask

Can primary key be non clustered?

Yes you can, by specifying the primary key be nonclustered.

Can we create primary key without clustered index?

The answer is NO. It is not possible at all. If I have to say in the most simple words, Primary Keys exists with either Clustered Index or Non-Clustered Index.

How can we change non clustered primary key to clustered primary key?

Taking all this into consideration, you cannot alter an index to make it clustered. However, you can create a new one so long as one does not already exist. Either that or drop the clustered index, create your new clustered index and then create your old clustered index as a non clustered index.


1 Answers

EF 6.2 resolved this issue. Currently, it's in beta state, but it works.

First, upgrade your EF to 6.2:

Install-Package EntityFramework -Version 6.2.0-beta1 -Pre

Then, in the OnModelCreating method, set the IsClustered to false for the primary key:

modelBuilder.Entity<Receipt>().HasKey(r => r.RecId, config => config.IsClustered(false) );
like image 116
Johnny Qian Avatar answered Oct 03 '22 21:10

Johnny Qian