Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Many-to-Many Clustered vs. Nonclustered Index

I designed an entity data model with two entities between which there exists a many to many relationship. When I auto-generate SQL code to generate the database for this model, it has generated a table (two columns) to keep track of this many-to-many association. However, this table has a PRIMARY KEY NONCLUSTERED on both columns.

Since I want this to work on SQL Azure which doesn't like tables with only nonclustered indices, I was wondering whether there is a good way of telling the code generation to generate clustered indices? Thanks!

like image 658
Jurgen Avatar asked Aug 25 '10 16:08

Jurgen


People also ask

Which is better clustered or nonclustered index?

A clustered index may be the fastest for one SELECT statement but it may not necessarily be correct choice. SQL Server indices are b-trees. A non-clustered index just contains the indexed columns, with the leaf nodes of the b-tree being pointers to the approprate data page.

What is the difference between clustered and non-clustered indexes?

A clustered index is used to define the order or to sort the table or arrange the data by alphabetical order just like a dictionary. A non-clustered index collects the data at one place and records at another place.

How many clustered & non-clustered index can you have on a table?

There can be only one clustered index per table, because the data rows themselves can be stored in only one order. The only time the data rows in a table are stored in sorted order is when the table contains a clustered index.

Does nonclustered index improve performance?

It contains only a subset of the columns. It also contains a row locator looking back to the table's rows, or to the clustered index's key. Because of its smaller size (subset of columns), a non-clustered index can fit more rows in an index page, therefore resulting to an improved I/O performance.


1 Answers

I have another file called Model.indexes.sql that contains scripts to create additional indexes beyond the basic ones EF generates, such as those for performance optimizations.

Although this is not ideal, I added into this an index drop and create for each EF association to convert the Non-Clustered indexes into indexed ones:

ALTER TABLE [dbo].[MyAssociation] DROP CONSTRAINT [PK_MyAssociation] GO ALTER TABLE [dbo].[MyAssociation] ADD CONSTRAINT [PK_MyAssociation] PRIMARY KEY CLUSTERED ([Table1_Id], [Table2_Id] ASC); GO

This is executed after every "Generate Database from Model...". I would love a more elegant solution.

like image 147
CodeGrue Avatar answered Sep 20 '22 04:09

CodeGrue