Removing many to many entity Framework

Standard way is to load the artist including the current related types from the database and then remove the types with the selected Ids from the loaded types collection. Change tracking will recognize which types have been removed and write the correct DELETE statements to the join table:

var artist = this._db.Artists.Include(a => a.ArtistTypes)
    .SingleOrDefault(a => a.ArtistID == someArtistID);

if (artist != null)
{
    foreach (var artistType in artist.ArtistTypes
        .Where(at => vm.SelectedIds.Contains(at.ArtistTypeID)).ToList())
    {
        artist.ArtistTypes.Remove(artistType);
    }
    this._db.SaveChanges();        
}

Leave a Comment

tech