2
public class User 
{ 
    public int Id {get;set;} 

    public string Name {get;set} 

    public ICollection<User> Followers {get;set;} 
    public ICollection<User> Following {get;set;} 
} 

我的模型看起來像以上,實體框架自動創建一個表,並UserUser與行User_IDUser_ID1在DB映射這種模式。我想自己映射表格和行。實體框架代碼優先:自定義映射

我該怎麼做,Thanx!

回答

2

Scott Gu's blogMany-valued Associations

許多-to-many關聯 類別和項目之間的關聯是一個許多一對多 關聯,如在上面的類圖中可以看出。多對多 關聯映射隱藏了 應用程序的中間關聯表,因此您的域模型中不會出現不需要的實體。這就是說,在一個真實的系統中,你可能沒有一個多對多的關聯,因爲我的經驗是,幾乎有 必須附加到關聯實例(如日期和時間)之間的每個鏈接上的其他信息當一個項目被添加到一個類別中時 ),並且通過中間關聯類表示此信息的最佳方式是 (在EF中,您可以將關聯類映射爲實體並映射兩個一對多關聯 對任何一方)。

在多對多關係中,連接表(或鏈接表,如一些 開發人員稱之爲)具有兩列:類別 和項目表的外鍵。主鍵是兩列的組合。 在EF 代碼首先,許多-to-many關聯映射可以用 定製這樣一個流暢的API代碼:

class ItemConfiguration : EntityTypeConfiguration<Item> { 
    internal ItemConfiguration() 
    { 
     this.HasMany(i => i.Categories) 
      .WithMany(c => c.Items) 
      .Map(mc => 
      { 
       mc.MapLeftKey("ItemId"); 
       mc.MapRightKey("CategoryId"); 
       mc.ToTable("ItemCategory"); 
      }); 
    } } 

註冊此配置在您的DbContext的(你使用的DbContext API嗎? )像這樣:

protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
    base.OnModelCreating(modelBuilder); 

    modelBuilder.Configurations.Add(new ItemConfiguration()); 
    } 

祝你好運,希望這能幫到你!

2

一個實體映射到自己,你會做這樣的事情

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<User>().HasMany(u => u.Followers) 
     .WithMany().ForeignKey(u => u.FollowerId); 

    base.OnModelCreating(modelBuilder); 
} 

它很難說沒有看到,雖然你的數據庫模型,以及如何確實和追隨者給用戶。