Base solution for your next web application
Open Closed

Duplicate ID's on database #9638


0
Ricavir created

Prerequisites

  • Angular
  • .net core

If issue related with ABP Framework

  • 5.7.0

I've created a manager class on server side to generate ID's without same values. You'll find the code below :

[UnitOfWork(IsolationLevel.ReadUncommitted)]
        public virtual async Task GenerateSuccessiveId(Event eventToManage)
        {
            using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
                eventToManage.SuccessiveId = (await _eventRepository.GetAll().Where(ev=>ev.TenantId == eventToManage.TenantId).MaxAsync(s => s.SuccessiveId)) + 1;

            long nextEventId = await SettingManager.GetSettingValueForTenantAsync<long>(AppSettings.TenantSuccessiveId.NextEventId, eventToManage.TenantId);
            if (eventToManage.SuccessiveId < nextEventId)
                eventToManage.SuccessiveId = nextEventId;
        }

This has been working great for the last 2 years. But I had a case recently where 3 requests came in a very short time to the server. It results in the following behavior :

  • First request : SuccessiveId = 932 --> OK
  • Second request : SuccessiveId = 933 --> OK
  • Third request : SuccessiveId = 933 --> NOK

Do you see any mistake in this code block ?


3 Answer(s)
  • 0
    ismcagdas created
    Support Team

    Hi,

    If you want below code to generate unique numbers;

    (await _eventRepository.GetAll().Where(ev=>ev.TenantId == eventToManage.TenantId).MaxAsync(s => s.SuccessiveId)) + 1;

    You need to use lock in generation of this code. It must be thread safe.

  • 0
    Ricavir created

    Hi @ismcagdas,

    I will try to convert to a thread less method and add a lock. Thanks

  • 0
    ismcagdas created
    Support Team

    Hi @ricavir

    Thanks. Please reopen if you can't solve this problem and share your final code.