abp icon indicating copy to clipboard operation
abp copied to clipboard

FindAsync does not get inserted record without SaveChanges

Open eneskoroglu opened this issue 5 years ago • 2 comments

  • Your ABP Framework version: 4.3.3
  • Your User Interface type (Angular/MVC/React... etc.): Angular
  • Your database provider(EF Core/MongoDB): EF Core

I have a list of products and getting their stock from database with FindAsync(). If FindAsync() does not get record I insert product to stock with InsertAsync(). And then if i call FindAsync() second time for same Product Id, i still do not get Stock record and my code tries to insert record to Stock second time. I need to Find stock of product and if stock exists, update stock quantity. How can i find also newly inserted records without calling SaveChangesAsync() in foreach loop.

foreach (var product in products)
{
    var stock = await stockRepository.FindAsync(product.Id);
    if (stock == null)
    {
        stock = new Stock(SequenceGenerator.Create(SequenceType.Default), product.Id, quantity);
        stock = await stockRepository.InsertAsync(stock);
    }
    else
    {
        stock.Quantity += quantity;
        stock = await stockRepository.UpdateAsync(stock);
    }                
    await uow.SaveChangesAsync();              
}

eneskoroglu avatar Oct 07 '21 08:10 eneskoroglu

In the same UnitOfWork, you can not. Transaction still waiting to be executed until you finish all jobs.

  1. You can disable unit of work for your single method with [UnitOfWork(false)] attribute:
[UnitOfWork(false)]
public async Task<Stock> GetStockAsync()
{
    //...
}

  1. In the another way you can make Insert operation out of UnitOfWork via sending autoSave parameter as true
stock = await stockRepository.InsertAsync(stock, autoSave: true);

enisn avatar Oct 07 '21 09:10 enisn

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Dec 07 '21 05:12 stale[bot]