Removing many to many entity Framework

后端 未结 2 768
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 18:24

There is a many to many relationship between Artist and ArtistType. I can easily add artist ArtistType like below

fore         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 18:57

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

提交回复
热议问题