Entity Framework Code First Fluent Api: Adding Indexes to columns

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

    expanding on Petoj

    i modified the CreateIndexQueryTemplate to

    private const string CreateIndexQueryTemplate = "IF NOT EXISTS (SELECT name FROM sysindexes WHERE name = '{indexName}') CREATE {unique} INDEX {indexName} ON {tableName} ({columnName});";
    

    and removed the following from OnModelCreating

    Database.SetInitializer(new IndexInitializer<MyContext>());
    

    and added the following to Configuration Seeding method

    new IndexInitializer<MyContext>().InitializeDatabase(context);
    

    this way the index attributes are run every time you do a update-database.

    0 讨论(0)
  • 2020-11-30 18:25

    Note that in Entity Framework 6.1 (currently in beta) will support the IndexAttribute to annotate the index properties which will automatically result in a (unique) index in your Code First Migrations.

    0 讨论(0)
  • 2020-11-30 18:31

    You can specify index in ModelBuilder

    modelBuilder
                .Entity<UserSalary>(builder =>
                {
                    builder.HasNoKey();
                    builder.HasIndex("UserId").IsUnique(false);
                    builder.ToTable("UserSalary");
                });
    
    0 讨论(0)
提交回复
热议问题