akd akd - 2 months ago 20
C# Question

Removing many to many entity Framework

There is a many to many relationship between

Artist
and
ArtistType
. I can easily add artist
ArtistType
like below

foreach (var artistType in this._db.ArtistTypes
.Where(artistType => vm.SelectedIds.Contains(artistType.ArtistTypeID)))
{
artist.ArtistTypes.Add(artistType);
}

_db.ArtistDetails.Add(artist);
_db.SaveChanges();


This goes and updates the many to many association table with correct mapping. But when I try to remove any item from table I do not get any error but it does not remove it from the table?

foreach (var artistType in this._db.ArtistTypes
.Where(at => vm.SelectedIds.Contains(at.ArtistTypeID)))
{
artistDetail.ArtistTypes.Remove(artistType);
}

this._db.Entry(artistDetail).State = EntityState.Modified;
this._db.SaveChanges();


What am I missing?

Answer Source

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();        
}