I am performing a read operation from the XLS file and doing the insert if the data is not present in the table.
DB Operation:
foreach (var transaction in transactions)
{
if (!_dbContext.Transactions.Any(t =>
t.TransactionDate.Date == transaction.TransactionDate.Date &&
t.ValueDate.Date == transaction.ValueDate.Date &&
t.Balance == transaction.Balance &&
t.ChequeNumber!.Trim() == transaction.ChequeNumber!.Trim() &&
t.TransactionRemarks.Trim() == transaction.TransactionRemarks.Trim() &&
t.WithdrawalAmount == transaction.WithdrawalAmount &&
t.DepositAmount == transaction.DepositAmount))
{
_dbContext.Transactions.Add(transaction);
}
}
await _dbContext.SaveChangesAsync();
DBContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Transaction>()
.HasKey(t => new {
t.TransactionDate,
t.ValueDate,
t.Balance,
t.ChequeNumber,
t.TransactionRemarks,
t.WithdrawalAmount,
t.DepositAmount
});
}
The XLS file has some duplicate data and to avoid the duplicate insert I already have an if statement that will not add data to the context. However, the code is not working the way it should and I am getting the below error:
The instance of entity type 'Transaction' cannot be tracked because another instance with the same key value for {'TransactionDate', 'ValueDate', 'Balance', 'ChequeNumber', 'TransactionRemarks', 'WithdrawalAmount', 'DepositAmount'} is already being tracked.
Transaction Model:
public class Transaction
{
[NotMapped]
public int SNo { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public DateTime ValueDate { get; set; }
public DateTime TransactionDate { get; set; }
public string? ChequeNumber { get; set; }
public string TransactionRemarks { get; set; } = string.Empty;
public decimal? WithdrawalAmount { get; set; }
public decimal? DepositAmount { get; set; }
public decimal Balance { get; set; }
}
What am I doing wrong?
5
Thanks to @Gert Arnold
for his answer. The solution was to filter the list first. Because the list consisted of duplicate records it makes much more sense to make it distinct. For that, I used DistinctBy
as suggested by Gert.
DistinctBy(x => new { x.Key1, x.Key2 })