Using HiLo algorithm for client side ID generation with EF Core

The benefit of HiLo algorithm over using Guid as datatype of ID columns, is that, with HiLo we can use integer datatype for client side ID generation, and integer datatype is better in performance than Guid. Added advantage is with integer datatype, the information of the order in which records were inserted in a table is also maintained.

In the DB Context class, this is how we can tell EF Core to use HiLo algo to generate ID values for all entities:

protected override void OnModelCreating(ModelBuilder modelbuilder)
{
    modelbuilder.UseHiLo();
}

Below configuration can be used, to enable the HiLo algorithm for entities selectively, rather than for all entities:

modelbuilder.Entity<Category>()
            .Property(o => o.CategoryID).ForSqlServerUseSequenceHiLo();

Client side ID generation is beneficial when we need to save data changes as a batch and ID of newly inserted record is required for a subsequent changes; an example is shown below:

var category1 = new Category() { CategoryName = "Clothing" };
dataContext.Categories.Add(category1); // This is the statement at which EF Core contacts DB to get next Hi value (only if Low 
                                       // values of current Hi are all used up) and calculates
                                       // the ID 

var product1 = new Product() { CategoryId = category1.ID, ProductName = "TShirts" }
dataContext.Products.Add(product1);
dataContext.SaveChanges();

The above batch would throw an exception if we use database side ID generation using identity column if Product(CaregoryId) is a foreign key, because in that case, ID of category record would not be available untill the statement “dataContext.SaveChanges()” is executed.

Leave a Comment

Your email address will not be published. Required fields are marked *