I need help trying to understand why my Blazor component in .net Core 6 is not updating my database when removing an entity, please take a look at my code sample: (beforehand, thanks for all your help!)
First, I'm injecting my db context as follow:
@inject AppDbContext db
then, below on my code, I decided to query for some data, in this case, Customers as follow:
@code {
private List<Customer> clients { get; set; }
protected override async Task OnInitializedAsync()
{
clients = await db.Customers.ToListAsync();
}
}
Now, I created a button with a method to delete the customer; first I search the entity, if found, then I remove the item from the "clients" list from the database, as follow:
private async Task DeleteCustomer(int CustomerId)
{
Customer? customer = clients.FirstOrDefault(f => f.Id == CustomerId);
if (customer is not null)
{
clients.Remove(customer);
await db.SaveChangesAsync();
}
}
THE PROBLEM is that the entity is removed from the list but not removed from the database, so when I refresh the item still there, I have to apply another command inside the if to make it work:
db.Remove(customer);
It seems to lose completely the connection between the list coming from the DB and the database. This is the first time I see something like this, am I missing something? am I using the EF the way I am supposed to do? I can just add that command and make it work but I don't think is a good practice, please help!