無負載建立多對多關聯的模型
原文中是Modeling a Many-to-Many Relationship with No Payload,雖然這麼翻譯也有點不準確,但是可以說明其目的,如下圖所示,資料庫中是這樣的關係,
我們按照Database Frist的開發模式,由嚮導建立模型,會得到幾個實體物件呢?
由此看出,這種多對多的關係賓補需要其它實體承載和轉換,那麼Modeling a Many-to-Many Relationship with No Payload也就這個意思咯。
再看看它是怎麼工作的:
using (var context = new EF6RecipesContext__1()) { // 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__1()) { 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); } } }
建立多對多關聯的模型並新增額外的資訊
上面的LinkTable只包含了兩個外來鍵資訊,EntityFramework並不會為此生成一個EntityType,但是如果LinkTable中附加了一些資訊,EntityFramework就會為此生成一個EntityType,形成兩個一對多的關聯如下:
那麼根據嚮導生成的實體關係圖如下:
再看看它是如何讓工作的【書中這段程式碼有點問題,現更正如下】
using (var context = new EF6_2RecipesContext()) { var order = new Order { OrderId = 1, OrderDate = new DateTime(2010, 1, 18) }; var item = new Item { SKU = 1729, Description = "Backpack", Price = 29.97M }; var oi = new OrderItem { Order = order, Item = item, Count = 1 }; context.OrderItems.Add(oi); item = new Item { SKU = 2929, Description = "Water Filter", Price = 13.97M }; oi = new OrderItem { Order = order, Item = item, Count = 3 }; context.OrderItems.Add(oi); item = new Item { SKU = 1847, Description = "Camp Stove", Price = 43.99M }; oi = new OrderItem { Order = order, Item = item, Count = 1 }; context.OrderItems.Add(oi); context.SaveChanges(); } using (var context = new EF6_2RecipesContext()) { foreach (var order in context.Orders) { Console.WriteLine("Order # {0}, ordered on {1}", order.OrderId,order.OrderDate); Console.WriteLine("SKU\tDescription\tQty\tPrice"); Console.WriteLine("---\t-----------\t---\t-----"); foreach (var oi in order.OrderItems) { Console.WriteLine("{0}\t{1}\t{2}\t{3}", oi.Item.SKU, oi.Item.Description, oi.Count, oi.Item.Price.ToString("C")); } } }
這也是書中推薦的建立多對多關係的方式,當然,專案的初期可能不需要新增額外的資訊,而形成的第一種多對多的模式,那麼書中也給出了最簡單也是最優的解決方案,就是在LinkTable中額外使用一個Int型別的標識列即可,這樣,到後期就可以體現出它的靈活性了。