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

后端 未结 4 1050
闹比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 11:04

    To solve your problem, after you generate your migration file, you must modify the generated code by disabling clustered index for your primary key by assigning false as a value of clustered parameter of PrimaryKey.

    After your modifications you must have something like this into your migration file:

    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");
    

    This is not done in OnModelCreating method by using Fluent API like Manish Kumar said, but in migration file. The file that is created when you use Add-Migration command.

    Existing Database

    As you say in comments, your database already exist. After executing Add-Migration command, you will have this line on your DbMigration file in your Up() method:

    public override void Up()
    {
        CreateIndex("dbo.UserProfiles", "UserID", clustered: true, name: "CI_UserProfiles_UserID");
    }
    

    You must modify the Up() method to have this code:

    public override void Up()
    {
        this.Sql("ALTER TABLE dbo.UserProfiles DROP CONSTRAINT \"PK_dbo.UserProfiles\"");
        this.Sql("ALTER TABLE dbo.UserProfiles ADD CONSTRAINT \"PK_dbo.UserProfiles\" PRIMARY KEY NONCLUSTERED (Id);");
        this.CreateIndex("dbo.UserProfiles", "UserID", clustered: true, name: "CI_UserProfiles_UserID");
    }
    

    In the code above I assumed that the created clustered index is named PK_dbo.UserProfiles in your database. If not then put at this place the correct name.

提交回复
热议问题