我有以下代码:
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();
}
using (var context = new EF6RecipesContext())
{
Console.WriteLine("Artists and their albums...");
var artists = context.Artists;
foreach (var artist in artists)
{
Console.WriteLine("{0} {1}", artist.FirstName, artist.LastName);
foreach (var album in artist.Albums)
{
Console.WriteLine("\t{0}", album.AlbumName);
}
}
Console.WriteLine("\nAlbums and their artists...");
var albums = context.Albums;
foreach (var album in albums)
{
Console.WriteLine("{0}", album.AlbumName);
foreach (var artist in album.Artists)
{
Console.WriteLine("\t{0} {1}", artist.FirstName, artist.LastName);
}
}
}
我得到了我的程序的以下结果(请参见截图):
在书中有不同的结果。
作者解释:
接下来,我们创建并初始化Artist实体类型的几个实例和Album实体类型的>实例。因为这两位艺术家合作了这张专辑,所以我们将这张专辑添加到两位艺术家的专辑导航属性(类型为> EntityCollection)。将相册添加到数据库上下文会导致艺术家获得 也加入了。
如果我们添加了专辑(“Honkytonk大学”),则应自动添加2个相关艺术家(“Tobby”和“Merle”)。但它们不会被添加(我查看了数据库)。为什么呢?