I'm getting the following error when trying to update to my database:
System.InvalidOperationException: 'The instance of entity type 'Expense' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
I think I'm missing some fundamental understanding. Trying to google this error mostly gives me answers of changing the service from singleton to scoped but mine is scoped. Here's the relevant code:
private async void SaveExpensesToDatabase()
{
foreach(Expense expense in expenses)
{
expense.CategoryName = expense.Category.Name;
Expense check = await expenseService.GetExpensebyKey(expense.Id);
if(check != null)
{
await expenseService.UpdateExpenseDetails(expense);
}
}
}
Here are the two functions in expenseService:
public async Task<Expense> GetExpensebyKey(string Id)
{
Expense expense = await _dbContext.Expenses.FirstOrDefaultAsync(x => x.Id == Id);
return expense;
}
public async Task<bool> UpdateExpenseDetails(Expense expense)
{
_dbContext.Expenses.Update(expense);
await _dbContext.SaveChangesAsync();
return true;
}
This is how I have my service listed in my Program file:
builder.Services.AddScoped<ExpenseService>();
I'm not just looking for how to make this work although that would be wonderful. I'm also looking for what fundamental concepts I'm not understanding. I think it's centered around how db context works. Thanks in advance!