EF - Add to the association set by the identifier

Say I have a lot of relationships:

Song *---* Artist 

I am at the point in my code where I want to add an artist to the song. I know the artist ID, but I do not have an instance of the Artist object.

Currently I need to do something like:

 var artist = context.Artists.Single(a => a.Id == artistId); song.Artists.Add(artist); 

This is due to a database query.

The many-to-many relationship is modeled as a table:

 SongId | ArtistId -------+--------- 

What I would like to do for performance reasons is to simply add an entry to this table without going to the database to load a bunch of entity data that I don't need.

Is there any way to do this using EF? For example, such an API:

 song.Artists.Add(artistId); 
+4
source share
1 answer

You can use a dummy object:

 var song = context.Songs.Single(s => s.Id == songId); var artist = new Artist { Id = artistId }; context.Artists.Attach(artist); song.Artists.Add(artist); context.SaveChanges(); 
+5
source

Source: https://habr.com/ru/post/1345898/


All Articles