question

GuillermoPerez-9757 avatar image
0 Votes"
GuillermoPerez-9757 asked GuillermoPerez-9757 edited

Entity Framework (EF) and .Net 6 Blazor not updating database

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!


dotnet-aspnet-core-blazordotnet-entity-framework-core
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @GuillermoPerez-9757,

I have to apply another command inside the if to make it work:

Can you tell us which command you are applied will make it work? You can add a Try-Catch statement to check if there have any exception when delete the entity?

Besides, please check the connection string, make sure you are using the same database.

And, after removing the entity and calling the SaveChange method, you need to re-query the data to get the latest/updated data, then display them. Besides, you can also check the database through the SQL Server Management Studio(SSMS), whether the data have already deleted in the database.




0 Votes 0 ·

Can you tell us which command you are applied will make it work?
Basically I have to remove the item from the list and then remove it from the DB, like this:

 //--- remove from the list...
 clients.Remove(customer);
 //---then remove it from the db...
             db.Remove(customer);
              await db.SaveChangesAsync();

I did check for errors but nothing. Usually, in other projects MVC, I query the db for wherever I'm looking for, when I have a set I put my desired records into a list with the tolist() linq method, and the items in the list are linked to the db, so if I remove something or update an entity on the list and then I save changes, my changes are in the database, that's not the case here... it seems the list is totally separated from the database, I can see the entities, the data, etc.. but any changes are simply ignored.

0 Votes 0 ·
BruceBarker-8516 avatar image
0 Votes"
BruceBarker-8516 answered GuillermoPerez-9757 edited

there is no connection between the client list

 clients = await db.Customers.ToListAsync(); 

and the database context. the list is just a list. your confusion may be because objects in the list are the same objects in DbContext. so if you update a property on an object in the list, it also updates the property for the same object in the DbContext.

but removing the object from the list, does not remove it from the DbContext.

· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

here's what I don't understand... in previous projects instead of going dbcontext.mytable.where(x => x.xxxx) I used to create my filter and store the result in a list, then if I deleted or modified an item, I did not go again against the db trying to search for this item. My understanding is that the list contains a reference to the entity which is monitored by EF, and it used to work fine, now is acting like we are cloning the objects into a completely separated or non-related list. am I the only one having this issue?

0 Votes 0 ·

as I said, the objects are the same objects in the dbcontext. You can find and modify the objects in the list. But removing or adding an object to the list has no impact on the dbcontext. how would it know the an item was was added or deleted from the list?

0 Votes 0 ·

@BruceBarker-8516 thank you for taking some time to answer, yes I do understand the adding new item, and make sense, as that was not part of the list but, what about the existing items? in other words, when using the "tolist()" (or async version) are these items cloned to a complete un-related object? if that's the case, how will thas perform the lazy loading of other entities... for example, Customer has a list of Pets, Pets have a list of notes... we load this with lazy loading... if these are un-related as you say, how these are loaded? My understanding is that existing items should be using a ref of the first object (in this case the dbcontext), otherwise it should be cloning, thanks for all your patience on helping me... :-)

0 Votes 0 ·
Show more comments
ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered

Hi @GuillermoPerez-9757,

   //--- remove from the list...
   clients.Remove(customer);
   //---then remove it from the db...
               db.Remove(customer);
                await db.SaveChangesAsync();

The above code and workflow are correct.

In your application, you are using the clients list to store the query records.

After query data from database, and store the records in the clients, the clients and the database have been completely separated.

Then, when you add/modify/delete the item in the clients it will not update the database. To update the data on clients and database, as the above code, you need to delete an item from the client and the database at the same time.

Besides, you could also delete the entity from database first, then update the clients list. Refer the following code:

  private async Task DeleteCustomer(int CustomerId)
  {    
      Customer? customer = clients.FirstOrDefault(f => f.Id == CustomerId);
    
      if (customer is not null)
      {    
          //---then remove it from the db...
          db.Remove(customer);
          await db.SaveChangesAsync()

          //re-query the database and update the clients

          clients = db.Customers.ToListAsync();
       }


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.