Removing many to many entity Framework

后端 未结 2 763
佛祖请我去吃肉
佛祖请我去吃肉 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();        
    }
    
    0 讨论(0)
  • 2020-12-05 19:07

    For removing only one field, I came up with this solution. It seems odd but in EF, most of the things are odd anyway because we try to tell EF the database ops in terms of OOP.

    using (var db = new Context())
    {
        //Create existing entities without fetch:
        var artist = new Artist() { ArtistID = _artistID };
        var type = new Type() { TypeID = _typeID };
    
        //Add one entity to other's list 
        //This is in memory, not connected.
        //So we do this because we try to tell EF that we want to remove this item
        //Without fetch, we should add it first in order to remove :)
        artist.ArtistTypes.Add(type);
    
        //Attach that entity which you add an item to its list:
        db.Artists.Attach(artist); 
        //It's now connected and recognized by EF as database operation
    
        //After attaching, remove that item from list and save db
        artist.ArtistTypes.Remove(type);
        db.SaveChanges();
    }
    

    That's it! With this solution, you are no longer fetching all entries of joined table ArtistTypes.

    0 讨论(0)
提交回复
热议问题