EF Core Code First - Clustered Index and Identity Column

.net-core entity-framework entity-framework-core

Question

I am using EF Core 2.0 to create a table in which the primary key is a GUID and the clustered index is an auto-incrementing INT column. But I'm getting this error:

Cannot create more than one clustered index on table 'Tenants'. Drop the existing clustered index 'PK_Tenants' before creating another

This is the code for creating entity and Fluent API.

Tenant.cs

public class Tenant : EntityBase
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ClusteredId { get; set; }
    public new Guid TenantId { get; set; }

    public string TenantCode { get; set; }
}

FluentAPI

protected override void OnModelCreating(ModelBuilder builder)
{
        builder.Entity<Tenant>().HasIndex(c => c.TenantId).ForSqlServerIsClustered(false);
        builder.Entity<Tenant>().HasIndex(c => c.ClusteredId).HasName("ClusteredId").ForSqlServerIsClustered(true);

        base.OnModelCreating(builder);
}

Please suggest, how to remove this error and create primary key for GUID and clustered index for auto-incrementing INT column.

Thanks.

1
1
5/16/2018 5:59:48 AM

Popular Answer

The PK index is not maintained explicitly. In EF Core it can be configured via KeyBuilder fluent API (note the HasKey in place of HasIndex):

    builder.Entity<Tenant>().HasKey(c => c.TenantId).ForSqlServerIsClustered(false);
    builder.Entity<Tenant>().HasIndex(c => c.ClusteredId).HasName("ClusteredId").ForSqlServerIsClustered(true);
2
5/16/2018 8:32:09 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow