Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
115 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...