简体   繁体   中英

Entity Framework: Best way to update related table

I have a structure like the following using EF:

An "Event" has many "Guests"

Let's say Event.Guests has 4 Guest elements, with the id's 1,2,3,4 I want to update the Event.Guests to have the guests with id's 3,4,5 (if Guest 5 doesn't exist I want to create it).

What's the most efficient way to remove the existing guests from Event and add the new one?

This is what I'm doing right now:

     var newGuests = new List<Guest>();
     var existingGuests = @event.Guests.ToList();

     // GetNewGuestsIds will return the new guests list (3,4,5)
     foreach (var guestId in GetNewGuestsIds())
     {
        Guest guest = existingGuests.FirstOrDefault(eg => eg.Id == guestId);

        if (guest == null)
        {
           guest = db.Guests.CreateObject();
           // fill guest data here
        }

        newGuests.Add(guest);
     }

     foreach (var existingGuest in existingGuests)
     {
        // Remove the existing element from the list to add
        var removed = newGuests.RemoveAll(g => g.Id == existingGuest.Id);
        if (removed == 0) // The existing host is not on the list to add, delete it
        {
           @event.EventHosts.Remove(existingGuest);
        }
     }

     foreach (var guest in newGuests)
     {
        @event.Guests.Add(guest);
     }

But I think this might be improved ... I just don't know how.

Thanks!

After some thought I came with this result which seems a lot better:

 var existingGuests = @event.Guests.ToList();

 // GetNewGuestsIds will return the new guests list (3,4,5)
 foreach (var guestId in GetNewGuestsIds())
 {
    if (existingGuests.RemoveAll(g => g.Id == guestId) == 0)
    {
       guest = db.Guests.CreateObject();
       // fill guest data here
       @event.Guests.AddObject(guest);
    }
 }

 existingGuests.ForEach(g => @event.Guests.Remove(g));

I hope this helps someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM