EF4中多对多关系表模型
数据库中有这样的三张表,Artist,Album,ArtistAlbum
Artist和Album是多对多的关系,ArtistAlbum 是Artist和Album的关联表。ArtistAlbum 是双主键,除了Artist和Album表的ID外没有其他任何其他字段。
新建一个项目,添加一个ADO.NET Entity Data Model,在数据库中选择上面三张表:
EMD中并没有关联表ArtistAlbum并没有作为一个实体呈现在EDM中
下面的代码是向Artist和Album表添加新的数据和在model中查询Artist的Album以及Album所属的Artist
代码
using (EFDemoEntities context = new EFDemoEntities())
{
// add an artist with two albums
var artist = new Artist { ArtistName = "徐悲鸿" };
var album1 = new Album { AlbumName = "八骏图" };
var album2 = new Album { AlbumName = "八丑图" };
artist.Albums.Add(album1);
artist.Albums.Add(album2);
context.Artists.AddObject(artist);
// add an album for two artists
var artist1 = new Artist { ArtistName = "zjz" };
var artist2 = new Artist { ArtistName = "张大千" };
var album = new Album { AlbumName = "大虾图" };
artist1.Albums.Add(album);
artist2.Albums.Add(album);
context.Albums.AddObject(album);
context.SaveChanges();
}
using (EFDemoEntities context = new EFDemoEntities())
{
Console.WriteLine("Artists and their albums...");
var artists = from a in context.Artists select a;
foreach (var artist in artists)
{
Console.WriteLine("{0}", artist.ArtistName);
foreach (var album in artist.Albums)
{
Console.WriteLine("\t{0}", album.AlbumName);
}
}
Console.WriteLine("\nAlbums and their artists...");
var albums = from a in context.Albums select a;
foreach (var album in albums)
{
Console.WriteLine("{0}", album.AlbumName);
foreach (var artist in album.Artists)
{
Console.WriteLine("\t{0}", artist.ArtistName);
}
}
}
{
// add an artist with two albums
var artist = new Artist { ArtistName = "徐悲鸿" };
var album1 = new Album { AlbumName = "八骏图" };
var album2 = new Album { AlbumName = "八丑图" };
artist.Albums.Add(album1);
artist.Albums.Add(album2);
context.Artists.AddObject(artist);
// add an album for two artists
var artist1 = new Artist { ArtistName = "zjz" };
var artist2 = new Artist { ArtistName = "张大千" };
var album = new Album { AlbumName = "大虾图" };
artist1.Albums.Add(album);
artist2.Albums.Add(album);
context.Albums.AddObject(album);
context.SaveChanges();
}
using (EFDemoEntities context = new EFDemoEntities())
{
Console.WriteLine("Artists and their albums...");
var artists = from a in context.Artists select a;
foreach (var artist in artists)
{
Console.WriteLine("{0}", artist.ArtistName);
foreach (var album in artist.Albums)
{
Console.WriteLine("\t{0}", album.AlbumName);
}
}
Console.WriteLine("\nAlbums and their artists...");
var albums = from a in context.Albums select a;
foreach (var album in albums)
{
Console.WriteLine("{0}", album.AlbumName);
foreach (var artist in album.Artists)
{
Console.WriteLine("\t{0}", artist.ArtistName);
}
}
}
输出结果如下: