I want to use client side generation GUID without the fragmentation cost it has in the DB side (I don't want to consider generating the primary key at the database side, as I want to leverage DDD and unit testing).
I am using SQL Server 2012 and Entity Framework 6.
- For that, i have created a table in sql server with:
And the entity
public partial class Mac { public Mac() { this.Id = Guid.NewGuid() } public System.Guid Id { get; set; } public string direccionMac { get; set; } }
- I understand this design will lead to table fragmentation. Therefore, as in here: https://stackoverflow.com/a/604842/310107 I added another column as clustered index named MyClusterKey (identity(1,1)).
So, Id, non clustered, and the primary key. MyClusterKey, clustered index, identity(1,1)
And the entity:
public partial class Mac
{
public Mac()
{
this.Id = Guid.NewGuid();
}
public System.Guid Id { get; set; }
public long MyClusterKey { get; set; }
public string direccionMac { get; set; }
}
MyClusteredKey added as DatabaseGeneratedOption.Identity:
public class MacMap : EntityTypeConfiguration<Mac>
{
public MacMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.MyClusterKey)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.direccionMac)
.IsRequired()
.IsFixedLength()
.HasMaxLength(16);
// Table & Column Mappings
this.ToTable("Macs");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.MyClusterKey).HasColumnName("MyClusterKey");
this.Property(t => t.direccionMac).HasColumnName("direccionMac");
}
}
- Another choice will be using option 1 (without the other clustered index), but with sequencial GuidComb as in https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/Id/GuidCombGenerator.cs
This will generate Guids in some order:
Questions:
- Is option 1 correctly implemented?
- What is the preferred option: 1, 2, 3 or neither and why?
- Option 3 is generating guid sorted only within the last part. This won't generate table fragmentation (if using the id as clustered key)?
- In option 2, the column MyClusterKey is used only to provide a clustered index and avoid table fragmentation ? Or it can have another use?