How to implement certain relation between two entities?

303 views Asked by At

I'm writing an app in asp.net MVC, and want to make models for my database using entity framework.

I want to make two entity models, song and playlist.

One playlist can, naturally, contain many songs, I suppose in that case I want to include

public List<Song> Songs { get; set; }

But, one song can be in more playlists, so how should I write song entity? Also

public List<Playlist> Playlists { get; set; }

?

In my app I want user to be able to add song to specific playlist. Only thing that comes into my mind is a little drop down menu next to a song that has listed all playlists which don't contain specific song, so I suppose I need song entity to have some kind of reference to all playlists which contain it.

1

There are 1 answers

0
Martin Noreke On BEST ANSWER

This article on how to configure a Many-To-Many relationship should have some answers for you.

You will need to modify the model during ModelCreation something like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

   modelBuilder.Entity<Song>()
               .HasMany<PlayList>(s => s.Playlists)
               .WithMany(p => p.Songs)
               .Map(cs =>
                        {
                            cs.MapLeftKey("PlayListID");
                            cs.MapRightKey("SongId");
                            cs.ToTable("PlayListSong");
                        });

}

You could also create this by creating your own class to sit in between:

public class PlayListSong
{
    public int PlayListID { get; set; }
    public int SongID { get; set; }
}

In database terms, this is known as an "Intersection Identity" table.