Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...