4

With the following simple entity class, EF4.1 Code-First will create Clustered Index for the PK UserId column when intializing the database.

    public class User
    {
        [Key]
        public int UserId { get; set; }
        public int AppId  { get; set; }
        public string UserName { get; set; }
    }

For performance sake, my design goals is to keep the generated Users table physical Clustered according to the AppId coulmn not to the PK.

On my Initializer class I've tried to manually drop the autogenerated PK clustered index and create whatever clustered index I need, but no clue here to predict the autogenerated name PK__Users__25518C17 for the index!

I'm new to Code-First world, and really don't know if there's any workaround for my design goals.

Thanks in advance

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
Hossam
  • 1,037
  • 2
  • 13
  • 17

1 Answers1

5

You don't need to predict name of auto generated index. You just need to select name of the index. For SQL server you can use query like:

SELECT I.Name
FROM sys.indexes AS I
INNER JOIN sys.tables AS T ON
    I.object_Id = T.object_Id
WHERE I.is_primary_key = 1 
    AND T.Name = 'Users'

Once you get the name in your custom initializer you can alter old index and create a new one.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Many thanks, this helped me alot to go on with my approach. but later I learned that I have to drop/recreate every index/relation to get the User table clusterd on the AppId. – Hossam Apr 29 '11 at 21:22
  • 2
    Very painful approach in real world applications!! Without annotations like [Key(NonClustered)] or [Index(Clustered)] and without custom Conventions, designing the database-first then code-first is my way to go! still open for suggestions or hints. Thanks once more. – Hossam Apr 29 '11 at 21:38
  • 1
    Hossam, I actually think you've come to the right conclusion. DB generation is really only intended for indescriminate schemas on simple applications that can be A) generated to any datasource - even a configurable one & B) are simple. Because not all data storage systems even know what a clustered index is, EF probably won't even deal with it... that means it is definitely time for you to manage your own schema. Using a DB project will mean you can import a generated DB and tweak it very easily. – Gats Apr 30 '11 at 06:43