EF Core - List update with deleting not more present items

Igor Baldacci 41 Reputation points
2022-12-06T11:19:20.207+00:00

Good morning,
to update a list of items I'm using this syntax, to verify if the item is present or not in the DB and so update or insert it as new item:

foreach (MyList mylist in lstMyLists)  
{  
    if(mylist.ItemId != 0)  
    {  
        _context.MyTable.Update(mylist);  
    }  
    else  
    {  
        _context.MyTable.Add(mylist);  
    }  
}  
  
await _context.SaveChangesAsync();  

Now my question is: if in the passed list (in my example "lstMyLists") some items where deleted, how can I check it?
I need e preliminary "select" command to verify if the deleted item exist or not, or there is a EF core command that check it automatically?
Which is the best way to use?

Thank you for any help.
Igor.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,196 Reputation points
    2022-12-06T16:13:45.777+00:00

    For EF Core, the following context is the DbContext and YourModel is the class/model to check for entity state and in this case Id is the primary key. Replace Console.WriteLine with your actions.

    List<EntityEntry> entries = context.ChangeTracker.Entries().Where(x => x.Entity is YourModel).ToList();  
      
    foreach (var entry in entries)  
    {  
     if (entry.State is EntityState.Added)  
     {  
     Console.WriteLine("Added");  
     }else if (entry.State is EntityState.Modified)  
     {  
     Console.WriteLine("Modified");  
     }else if (entry.State is EntityState.Unchanged)  
     {  
     Console.WriteLine("No changes");  
     }else if (entry.State is EntityState.Deleted)  
     {  
     Console.WriteLine($"Marked as deleted {((YourModel)entry.Entity).Id}");  
     }  
    }  
    

    Also, you can do the above by overriding SaveChangesAsync


1 additional answer

Sort by: Most helpful
  1. Igor Baldacci 41 Reputation points
    2022-12-06T16:08:52.343+00:00

    Very clear, thanks a lot for your replay.

    0 comments No comments