2016-09-29 196 views
7

我想要映射與同一個實體的多對多關係。該User實體有ContactsIList<User>數據字段,用於存儲用戶的聯繫人/朋友信息:實體框架核心:與同一個實體的多對多關係

public class User : DomainModel 
{ 
    public virtual IList<User> Contacts { get; protected set; } 
    //irrelevant code omitted 
} 

當我試圖用流利的API映射這個多對多的關係,它給我帶來些麻煩。顯然,當我在user.Contacts屬性上使用HasMany()時,它沒有WithMany()方法可以調用下一個。 Visual Studio的智能感知只顯示WithOne(),但不顯示WithMany()

modelBuilder.Entity<User>().HasMany(u => u.Contacts).WithMany() 
// gives compile time error: CS1061 'CollectionNavigationBuilder<User, User>' does not contain a definition for 'WithMany' and no extension method 'WithMany' accepting a first argument of type 

那麼爲什麼會發生這種情況呢?有什麼我做錯了映射這種多對多的關係?

+0

你可以看看這個:https://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many –

回答

15

那麼爲什麼會發生這種情況呢?有什麼我做錯了地圖這個多對多的關係嗎?

不,你沒有做錯任何事。 It's just not supported。當前狀態here

尚未支持沒有實體類代表 連接表的多對多關係。但是,您可以通過包含表的連接 的實體類並映射兩個單獨的一對多關係來表示多對多關係。

對於EF-Core,您應該爲映射表創建實體。如UserContacts。正如評論中提到的docs中的完整示例。我沒有實際測試下面的代碼,但它應該是這個樣子:

public class UserContacts 
{ 
    public int UserId { get; set; } 
    public virtual User User { get; set; } 

    public int ContactId { get; set; } // In lack of better name. 
    public virtual User Contact { get; set; } 
} 

public class User : DomainModel 
{ 
    public List<UserContacts> Contacts { get; set; } 
} 

和你modelBuilder

modelBuilder.Entity<UserContacts>() 
     .HasOne(pt => pt.Contact) 
     .WithMany(p => p.Contacts) 
     .HasForeignKey(pt => pt.ContactId); 

    modelBuilder.Entity<UserContacts>() 
     .HasOne(pt => pt.User) 
     .WithMany(t => t.Contacts) 
     .HasForeignKey(pt => pt.UserId); 
+0

在第一modelBulder.Entity,它應該是「.WithMany(p => p.Users)」而不是「.WithMany(p => p.Contacts)」? –

+0

@CarlosAdrián - 我想不是。因爲它是對同一張表的引用。它仍然是一個擁有多個聯繫人的用戶。聯繫人仍然是用戶。 – smoksnes