Entity Framework Code First Fluent Api: Adding Indexes to columns

前端 未结 15 1387
一生所求
一生所求 2020-11-30 17:43

I\'m running EF 4.2 CF and want to create indexes on certain columns in my POCO objects.

As an example lets say we have this employee class:

public c         


        
15条回答
  •  孤街浪徒
    2020-11-30 18:18

    I discovered a problem with the answer @highace gave - the down migration uses the wrong override for DropIndex. Here is what I did:

    1. To comply with Sql Server's limitation on index columns (900 bytes) I reduced the size of a couple of fields in my model
    2. I added the migration using Add-Migration "Add Unique Indexes"
    3. I manually added the CreateIndex and DropIndex methods to the migration. I used the override that takes the index name for the single column index. I used the override that takes an array of column names where the index spans more than one column

    And here is the code with examples of both overrides of each method:

    public partial class AddUniqueIndexes : DbMigration
    {
        public override void Up()
        {
            //Sql Server limits indexes to 900 bytes, 
            //so we need to ensure cumulative field sizes do not exceed this 
            //otherwise inserts and updates could be prevented
            //http://www.sqlteam.com/article/included-columns-sql-server-2005
            AlterColumn("dbo.Answers",
                "Text",
                c => c.String(nullable: false, maxLength: 400));
            AlterColumn("dbo.ConstructionTypes",
                "Name",
                c => c.String(nullable: false, maxLength: 300));
    
            //[IX_Text] is the name that Entity Framework would use by default
            // even if it wasn't specified here
            CreateIndex("dbo.Answers",
                "Text",
                unique: true,
                name: "IX_Text");
    
            //Default name is [IX_Name_OrganisationID]
            CreateIndex("dbo.ConstructionTypes",
                new string[] { "Name", "OrganisationID" },
                unique: true);
        }
    
        public override void Down()
        {
            //Drop Indexes before altering fields 
            //(otherwise it will fail because of dependencies)
    
            //Example of dropping an index based on its name
            DropIndex("dbo.Answers", "IX_Text");
    
            //Example of dropping an index based on the columns it targets
            DropIndex("dbo.ConstructionTypes", 
                new string[] { "Name", "OrganisationID" }); 
    
            AlterColumn("dbo.ConstructionTypes",
                "Name",
                c => c.String(nullable: false));
    
            AlterColumn("dbo.Answers",
                "Text",
                c => c.String(nullable: false, maxLength: 500));
    }
    

提交回复
热议问题