Removing many to many entity Framework

后端 未结 2 769
佛祖请我去吃肉
佛祖请我去吃肉 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 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.

提交回复
热议问题