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
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.
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.
Nope, it can be nonclustered.
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.
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:
The initilizer will make your solution dependent on the concrete database server product.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With