Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF CodeFirst create non-clustered primary key index

I'm using EF 4.1 CodeFirst to create my DB. It seems that EF is creating all primary keys with clustered index, which is not optimal for us in one case(possibly more cases). Is there a way to tell EF to generate this table with primary key as a non-clustered index ?

Of course we could do it manually using custom script after database is already created, but we have a lot of foreign keys pointing to this table, it would be quite a non-optimal solution if there is a better, more straight forward way to do the same already during DB creation. Any help appreciated

like image 638
petho Avatar asked Jul 25 '11 08:07

petho


People also ask

Can we create non-clustered index on primary key?

Indexes are automatically created when PRIMARY KEY and UNIQUE constraints are defined on table columns. For example, when you create a table with a UNIQUE constraint, Database Engine automatically creates a nonclustered index.

How do you create a non-clustered index?

Right-click the table on which you want to create a nonclustered index and select Design. Right-click on the column you want to create the nonclustered index on and select Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box.

Should primary key always be clustered index?

Nope, it can be nonclustered.

Why you should never use GUIDs as part of Clustered index?

The problem with clustered indexes in a GUID field are that the GUIDs are random, so when a new record is inserted, a significant portion of the data on disk has to be moved to insert the records into the middle of the table.


2 Answers

No there is no way to control SQL code first generates - it is code first and its current philosophy (the bad one actually) is: you know nothing about the database and you don't bother.

The only way to change this behavior is to write custom database initializer, use custom database queries to search for created index, remove that index and create a new one. Some references:

  • How to stop EF4.1 Code-First to create Culstered index for the entity PK
  • Custom initializer with adding an index
  • Example of more advanced initializer

The initilizer will make your solution dependent on the concrete database server product.

like image 81
Ladislav Mrnka Avatar answered Oct 19 '22 06:10

Ladislav Mrnka


Yes there is a way you can specify not to create Clustered Indexes. If you use code migrations, a *.cs file is generated in order to populate your DataBase. In this file you can specify apart from the Primary key for each table, if it needs to be created with clustered indexes.

  .PrimaryKey(t => t.MID, null, true)
like image 41
Fritjof Berggren Avatar answered Oct 19 '22 06:10

Fritjof Berggren