Database Reference
In-Depth Information
Figure 2-11. The model with a many-to-many relationship between our tables
The many-to-many relationship between Album and Artist is represented by a line with the * character on
both ends. Because an Album can have many Artists, and an Artist can responsible for many Albums, each of these
navigation properties is of type EntityCollection .
How It Works
In Figure 2-11 , an artist can be related to many albums, whereas an album can be the work of many artists. Notice
that the link table from Figure 2-10 is not represented as an entity in our model. Because our link table has no scalar
properties (that is, it has no payload), Entity Framework assumes that its sole purpose is to create the association
between Album and Artist. If the link table had scalar properties, Entity Framework would have created a very
different model, as we will see in the next recipe.
The code in Listing 2-3 demonstrates how to insert new albums and artists into our model and how to query our
model for both artists and their albums and albums with their artists.
Listing 2-3. Inserting and Querying Our Artists and Albums Model Through the Many-to-Many Association
using (var context = new EF6RecipesContext())
{
// add an artist with two albums
var artist = new Artist { FirstName = "Alan", LastName = "Jackson" };
var album1 = new Album { AlbumName = "Drive" };
var album2 = new Album { AlbumName = "Live at Texas Stadium" };
artist.Albums.Add(album1);
artist.Albums.Add(album2);
context.Artists.Add(artist);
// add an album for two artists
var artist1 = new Artist { FirstName = "Tobby", LastName = "Keith" };
var artist2 = new Artist { FirstName = "Merle", LastName = "Haggard" };
var album = new Album { AlbumName = "Honkytonk University" };
artist1.Albums.Add(album);
artist2.Albums.Add(album);
context.Albums.Add(album);
context.SaveChanges();
}
 
Search WWH ::




Custom Search