Base solution for your next web application
Open Closed

Preserve sequence of inserts #9421


User avatar
0
sumitshah created

Hello Team, In a table we are inserting multiple records using 'InsertAsync' in a for loop. Outside the loop we are calling 'await CurrentUnitOfWork.SaveChangesAsync()'.
So we need the records to be inserted in sequence but that is not happening... meaning suppose there are 20 records which are being inserted then the sequence of insert is not being preserved, it may insert 14th record before 2nd record. How can we preserve the sequence of inserts ?

Thank you


5 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    hi

    You can try to put the CurrentUnitOfWork.SaveChangesAsync method in the loop.

  • User Avatar
    0
    sumitshah created

    Hi,

    We have tried putting the CurrentUnitOfWork.SaveChangesAsync method in the loop and it does resolve the insert sequence issue but it also impacts the performance as insert query is being fired multiple times instead of only one time. So when multiple users are using the application and number of records being inserted by them is large then performance takes a hit.

    Is there any other way to preserve the insert sequence in a single commit ?

  • User Avatar
    0
    maliming created
    Support Team

    hi

    In fact, this is a problem with EF Core, because we use DbContext to add entities.

    Can you share your insert loop code?

  • User Avatar
    0
    sumitshah created

    Hi,

    Our implementation is pretty much straightforward.

    foreach (var item in .selections)
    {
        var segmentSelection = ObjectMapper.Map<SegmentSelection>(item);
        // Some data manipulation/processing
         await _segmentSelectionRepository.InsertAsync(segmentSelection);
    }
    await CurrentUnitOfWork.SaveChangesAsync();
    

    Doing so sequence is getting distorted in sql table and if we move CurrentUnitOfWork.SaveChangesAsync() inside the for loop it's taking a performance hit.

  • User Avatar
    0
    maliming created
    Support Team

    hi

    It's seems this is ef core problem https://github.com/dotnet/efcore/issues/11686