waqar confiz

waqar confiz

  • NA
  • 11
  • 2.7k

Why is EF core 5.0 inserting duplicate records?

Jun 7 2022 11:55 AM

Why is Entity Framework 5.0 inserting duplicate records in the Database in uncertain behavior when used .AddAsync() method for adding data.

I have checked the existing value from records before inserting but still occurs duplication of value in the Database.

Here is my code.

if (response.Item1.PurchasesItem.Any())
{
    foreach (var rec in response.Item1.PurchasesItem)
    {
        try
        {
            var exist = await _cFCDbContext.PurchaseSaleLog.Where(a => a.IsActive && a.ProductCode == rec.ItemId.Trim() && a.DaxDate.Equals(rec.PurchDate) && !a.IsDeleted).OrderByDescending(a => a.Id).FirstOrDefaultAsync();
            if (exist == null)
            {
                var purchase = new PurchaseSaleLog()
                {
                    ProductCode = rec.ItemId,
                    VendorId = rec.VendorId,
                    Type = ServiceType,
                    PUOM = rec.UOM,
                    Quantity = (rec.PurchQty.Equals("")) ? 0 : Convert.ToInt32(rec.PurchQty),
                    Branch = rec.Branch,
                    BranchStock = (rec.BranchStock.Equals("")) ? 0 : Convert.ToInt32(rec.BranchStock),
                    DaxDate = rec.PurchDate,
                    IsActive = true,
                    IsDeleted = false,
                    CreatedBy = userId,
                    CreatedDate = DateTime.UtcNow,
                    ModifiedBy = userId,
                    ModifiedDate = DateTime.UtcNow
                };
                await _cFCDbContext.PurchaseSaleLog.AddAsync(purchase);
                await _cFCDbContext.SaveChangesAsync().ConfigureAwait(false);
            }
            else
            {
                exist.ProductCode = rec.ItemId;
                exist.VendorId = rec.VendorId;
                exist.Type = ServiceType;
                exist.Quantity = (rec.PurchQty.Equals("")) ? 0 : Convert.ToInt32(rec.PurchQty);
                exist.Branch = rec.Branch;
                exist.PUOM = rec.UOM;
                exist.BranchStock = (rec.BranchStock.Equals("")) ? 0 : Convert.ToInt32(rec.BranchStock);
                exist.DaxDate = rec.PurchDate;
                exist.ModifiedBy = userId;
                exist.ModifiedDate = DateTime.UtcNow;
                _cFCDbContext.PurchaseSaleLog.Update(exist);
                await _cFCDbContext.SaveChangesAsync().ConfigureAwait(false);
            }

        }
        catch (Exception ex)
        {
            continue;
        }
    }
}

 


Answers (2)