本文摘抄自:http://www.tuicool.com/articles/JRjQZz
在上一篇轉載的文章中,缺少了多對多的配置。實踐的時候發現使用中間表實現多對多的時候,如果在Fluent API中不指定外鍵,還是會有些問題。有時候會出現"xxx_Id"不存在這樣的錯誤。所以手動指定肯定不會有問題,實現如下:
添加一個活動類Activity,跟旅行類Trip是多對多的關係。這個也不難理解:一個旅行有多個活動,一個活動可以屬於多個旅行。
/// <summary> /// 活動類 /// </summary> public class Activity { public int ActivityId { get; set; } //[Required, MaxLength(50)] public string Name { get; set; } public List<Trip> Trips { get; set; } //和Trip類是多對多關係 }
跟之前的一樣在BreakAwayContext類裏添加Activity類,讓數據庫上下文知道Activity類:
public DbSet<CodeFirst.Model.Activity> Activitys { get; set; }
同時在Trip旅行類裏添加上導航屬性,形成跟Activity活動類的多對多關係
public List<Activity> Activitys { get; set; }
ok,已經可以了,跑下程序得到如下數據庫:
可以看出,EF裏的多對多關係是由第三張表來連接兩個表的。ActivityTrips表連接了Activityes表和Trips表。表名列名都是默認命名,都可以自己配置。文章的開頭已經說了那麼多了,多對多肯定是用HasMany和WithMany方法,在ActivityMap類裏寫下如下Fluent API:
this.HasMany(a => a.Trips).WithMany(t => t.Activitys).Map(m => { m.ToTable("TripActivities"); //中間關係表表名 m.MapLeftKey("ActivityId"); //設置Activity表在中間表主鍵名 m.MapRightKey("TripIdentifier"); //設置Trip表在中間表主鍵名 });
同樣也可以在TripMap裏配置,順序不一樣罷了:
this.HasMany(t => t.Activities).WithMany(a => a.Trips).Map(m => { m.ToTable("TripActivities"); //中間關係表表名 m.MapLeftKey("TripIdentifier"); //設置Activity表在中間表的主鍵名 m.MapRightKey("ActivityId"); //設置Trip表在中間表的主鍵名 });