非群集主要密钥实体框架代码优先

时间:2016-06-16 09:24:18

标签: indexing entity-framework-6

在Entity Framework Code First方法中,我们可以将主键定义为非聚簇索引,并将其他几个字段组合为聚簇索引。

由于

4 个答案:

答案 0 :(得分:11)

EF 6.2解决了这个问题。目前,它处于测试状态,但它确实有效。

首先,将您的EF升级到6.2:

Install-Package EntityFramework -Version 6.2.0-beta1 -Pre

然后,在OnModelCreating方法中,将IsClustered设置为false作为主键:

modelBuilder.Entity<Receipt>().HasKey(r => r.RecId, config => config.IsClustered(false) );

答案 1 :(得分:3)

EntityTypeConfiguration不提供将主键设置为非聚集索引的方法,但您可以通过更改用于创建表的初始迁移来完成此操作。有一个例子here

以下是如何使用属性指定群集多列索引的示例:

[Index("IX_ColumnOneTwo", 1, IsClustered = true)]
public int ColumnOne { get; set;}

[Index("IX_ColumnOneTwo", 2, IsClustered = true)]
public int ColumnTwo { get; set; }

以及如何使用模型构建器完成此操作的示例:

modelBuilder.Entity<ClassOne>() 
            .Property(t => t.ColumnOne) 
            .HasColumnAnnotation( 
                     "Index",  
                     new IndexAnnotation(new IndexAttribute("IX_ColumnOneTwo") { IsClustered = true }));
modelBuilder.Entity<ClassOne>() 
            .Property(t => t.ColumnTwo) 
            .HasColumnAnnotation( 
                     "Index",  
                     new IndexAnnotation(new IndexAttribute("IX_ColumnOneTwo") { IsClustered = true }));

答案 2 :(得分:3)

通过覆盖DbContext中的OnModelCreating,有一个Entity Framework Core Code First的解决方案

 table.PrimaryKey("PK_Columns", x => x.ColumnId)
                        .Annotation("SqlServer:Clustered", false);

此代码将生成如下迁移:

{{1}}

答案 3 :(得分:0)

Radenko Zec的{​​{3}}在EF Core中也非常有用。我将在此基础上提供一个用于控制命名的完整解决方案,并在需要时提供一个标识。我将从我的一个项目中选择一个示例:

NLog

NLogId - Primary Key, non-clustered, identity
EnteredDate - Clustered index
<other columns>

在EF Core中,您需要:

  1. 使用[Key]属性装饰NLogId属性
  2. 使用数据库上下文OnModelCreating覆盖自定义密钥:

    entity
        .HasKey(p => p.NlogId)
        .ForSqlServerIsClustered(false).HasName("PK_NLog");
    
    entity
        .HasIndex(p => p.EnteredDate)
        .ForSqlServerIsClustered(true).HasName("IDX_NLog_EnteredDate");
    
  3. 再次检查是否生成了身份代码(之后添加身份更加困难):

    migrationBuilder.CreateTable(
        name: "NLog",
        columns: table => new
        {
            NLogId = table.Column<int>(nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),