Entity Framework Code First Fluent Api: Adding Indexes to columns

前端 未结 15 1350
一生所求
一生所求 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:07

    After Migrations was introduced in EF 4.3 you can now add indexes when modifying or creating a table. Here is an excerpt from the EF 4.3 Code-Based Migrations Walkthrough from the ADO.NET team blog

    namespace MigrationsCodeDemo.Migrations
    {
        using System.Data.Entity.Migrations;
    
        public partial class AddPostClass : DbMigration
        {
            public override void Up()
            {
                CreateTable(
                    "Posts",
                    c => new
                        {
                            PostId = c.Int(nullable: false, identity: true),
                            Title = c.String(maxLength: 200),
                            Content = c.String(),
                            BlogId = c.Int(nullable: false),
                        })
                    .PrimaryKey(t => t.PostId)
                    .ForeignKey("Blogs", t => t.BlogId, cascadeDelete: true)
                    .Index(t => t.BlogId)
                    .Index(p => p.Title, unique: true);
    
                AddColumn("Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3));
            }
    
            public override void Down()
            {
                DropIndex("Posts", new[] { "BlogId" });
                DropForeignKey("Posts", "BlogId", "Blogs");
                DropColumn("Blogs", "Rating");
                DropTable("Posts");
            }
        }
    }
    

    This is a nice strongly typed way to add the indexes, which was what i was looking for when i first posted the question.

提交回复
热议问题