[英]How to use Database Migrations and EF 4.3 with a code first approach to create relationship tables?
我一直在嘗試使用Scott Gu在Tech Days中使用的MVC 4.0和數據庫遷移,並且遇到了存在多對多關系時創建的數據庫的問題。
http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2364:21:14開始
包括用於生成數據庫的代碼片段,如下圖所示。
public class Trip {
public int ID { get; set; }
public string Name { get; set; }
public DateTime Begin { get; set; }
public DateTime End { get; set; }
public Location HomeCountry { get; set; }
//public IList<Location> Itinerary { get; set; }
public ICollection<Location> Itinerary { get; set; }
public Trip()
{
this.Itinerary = new HashSet<Location>();
}
}
public class Location
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Trip> Trips { get; set; }
public Location()
{
this.Trips = new HashSet<Trip>();
}
}
這是結果數據庫。 (我會發布一張圖片,但我無法發布圖片,仍然是新用戶)
Tables Locations PK ID (int) Name (varchar) Trip_ID (int) Trips PK ID (int) Name (varchar) Begin (datetime) End (datetime) HomeCountry_ID (int)
我想我會期望為Locations和Trips之間的多對多關系創建第三個關系表(許多Locations可以應用於許多Trips),而不是將Trip_Id列添加到Locations表。 有誰知道我在這里做錯了什么? 有沒有辦法讓數據庫自動化正確創建這些表?
在此先感謝您的所有幫助!
更新:我找到了以下鏈接,但我仍然無法使用EF 4.3使其工作。 我還編輯了我的代碼片段以反映以下帖子。
http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First
我終於能夠使用我添加到我更新的問題中的鏈接正確創建表格,但仍然沒有真正在解決方案上出售。 在我的Db Context類中,我添加了方法[protected override void OnModelCreating(DbModelBuilder modelBuilder)]。
public class MyTesterContext : DbContext
{
public MyTesterContext () : base("name=MyTesterContext ")
{
}
public DbSet<Trip> Trips { get; set; }
public DbSet<Location> Locations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Trip>().
HasMany(t => t.Itinerary).
WithMany(l => l.Trips).
Map(
m =>
{
m.MapLeftKey("TripID");
m.MapRightKey("LocationID");
m.ToTable("TripLocations");
});
}
}
新數據庫現在如下所示:
Tables Locations PK ID (int) Name (varchar) TripLocations TripID (int) LocationID (int) Trips PK ID (int) Name (varchar) Begin (datetime) End (datetime) HomeCountry_ID (int)
在代碼項目討論中它說:
http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First
因此,現有關系表存在一個小問題。 我們可以通過重寫OnModelCreating方法並使用Code First Fluent API添加映射來解決問題。
由於我沒有現有的關系表,老實說我不認為這個步驟是必需的,但我一直無法找到任何其他方法來創建正確的表結構。 希望隨着我對該技術越來越熟悉,我可以找到一種方法來要求覆蓋OnModelCreating方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.