-
Notifications
You must be signed in to change notification settings - Fork 24
Add a clustered index to your database
stefffdev edited this page Jul 21, 2020
·
3 revisions
To add records in a offline scenario, every added record needs a unique id. This is not possible when using integer values as keys, so GUID ids are used.
Because Azure SQL mirrors your database to multiple servers a clustered index is required to do that in a effective way, see https://azure.microsoft.com/en-us/blog/why-do-i-need-a-clustered-index/ for more information.
To use the GUID id as clustered index is less performant than a integer id, therefore we are adding a ClusteredIndex column to all our data tables, but since this column is only relevant to the server it is never synced to the client.
The configuration of this columns has to be done per table in the OnModelCreating method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// use a different clustered index than the string Id for performance reasons,
// this should be done for every table!
// the guid id should not be the clustered index
modelBuilder.Entity<NubeOperation>().HasKey(e => e.Id).IsClustered(false);
// add a ClusteredIndex column with auto-generated values
modelBuilder.Entity<NubeOperation>().HasIndex(e => e.ClusteredIndex).IsClustered();
modelBuilder.Entity<NubeOperation>().Property(e => e.ClusteredIndex).ValueGeneratedOnAdd();
modelBuilder.Entity<TodoItem>().HasKey(e => e.Id).IsClustered(false);
modelBuilder.Entity<TodoItem>().HasIndex(e => e.ClusteredIndex).IsClustered();
modelBuilder.Entity<TodoItem>().Property(e => e.ClusteredIndex).ValueGeneratedOnAdd();
}```