Hello there,
In my Blazor Server application, I am inserting a list of data into a database as follows with EF Core 6;
public async Task AddStockAsync(List gameBank)
{
await _oyunPalasContext.GameBanks.AddRangeAsync(gameBank);
await _oyunPalasContext.SaveChangesAsync();
}
I wonder if I can check the serial and pin inserted before? I am using an SQL server and EF Core 6.
public partial class GameBank
{
public int GameBankId { get; set; }
public Guid ReferenceId { get; set; }
public string? ProductCode { get; set; }
public int Quantity { get; set; }
public string? Version { get; set; }
public DateTime? RequestDateTime { get; set; } = DateTime.Now;
public int? CustomerId { get; set; }
public string? Password { get; set; }
public DateTime? ResponseDateTime { get; set; } = DateTime.Now;
public string? InitiationResultCode { get; set; }
public string? CompanyToken { get; set; }
public int Used { get; set; }
public string? ProductDescription { get; set; }
public string? Currency { get; set; }
public double UnitPrice { get; set; }
public double TotalPrice { get; set; }
public string? ApplicationCode { get; set; }
public double EstimateUnitPrice { get; set; }
public string? ValidatedToken { get; set; }
public string? Signature { get; set; }
public int Status { get; set; }
public virtual GameBankPin coupons { get; set; }
public string? ClientTrxRef { get; set; }
}
public partial class GameBankPin
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int GameBankId { get; set; }
public DateTime? ExpiryDate { get; set; }
public string? Serial { get; set; }
public string? Pin { get; set; }
public virtual GameBank GameBanks { get; set; }
}
There are tens of thousands of data in the database and the list to be compared (List
Mohamed Azarudeen ZPosted Jun 5, 2023, 1:06 PM
Hi ray
Instead of checking each record in a loop, you can query the database once to determine if any matching records exist. Here's an example of how you can modify your
AddStockAsyncmethod to incorporate this approach:In this modified code, the
serialsandpinsvariables extract the serial and pin values from thegameBanklist. Then, a query is performed usingWhere()to retrieve any matching records from the database. TheexistingRecordsvariable will contain the records that already exist.Next, the
newGameBanksvariable filters out the records from thegameBanklist that have matching serial and pin values in theexistingRecordslist.Finally, only the new records are added to the database using
AddRangeAsync(), andSaveChangesAsync()is called to persist the changes.Sam HobbsPosted Jun 5, 2023, 7:23 PM
I want to add that you can probably increase performance by creating indexes for serial and pin.