How to change a clustered index in Entity Framework 6.1 Code First model and apply it to an Azure database

后端 未结 4 1015
闹比i
闹比i 2021-01-18 10:31

Using the Entity Framework 6.1 code first model, what is the best way to go about changing the clustered index on a table from the default ID to another set of columns. Azur

4条回答
  •  天涯浪人
    2021-01-18 10:51

    After the migration file is created, modify the generated code, disabling the clustered index for the primary key by setting the clustered property to false.

    Being that Azure does not allow a table without a clustered index, and there is no utility in SQL Server to 'change' a clustered index on a table, it is necessary create a new table with the clustered index and migrate the existing data to it. The code below renames the original table, migrates the data to the new table that was created with the new clustered index and drops the original table.

            RenameTable("dbo.UserProfiles", "UserProfiles_PreMigrate");
    
            CreateTable(
                "dbo.UserProfiles",
                c => new
                {
                    Id = c.Guid(nullable: false),
                    UserID = c.Guid(nullable: false),
                    FieldID = c.Guid(nullable: false),
                    Value = c.String(nullable: false, maxLength: 400),
                })
                .PrimaryKey(t => t.Id, clustered: false)
                .Index(t => t.UserID, clustered: true, name: "CI_UserProfiles_UserID");
    
            Sql(@"
                INSERT [dbo].[UserProfiles]
                (ID,
                 UserID,
                 FieldID,
                 Value)
                SELECT
                 ID,
                 UserID,
                 FieldID,
                 Value
                FROM dbo.UserProfiles_PreMigrate
    
            ");
    
            DropTable("UserProfiles_PreMigrate");
    

    Any existing table constraints will be lost in this operation, so it will be necessary to recreate and indexes,foreign keys, etc on the table.

提交回复
热议问题