[英]Entity Framework Core: many-to-many relationship with the same object
[英]Entity Framework Core: many-to-many relationship with same entity
我正在嘗試映射與同一實體的多對多關系。 User
實體有一個IList<User>
數據字段用於Contacts
,它存儲用戶的聯系人/朋友信息:
public class User : DomainModel
{
public virtual IList<User> Contacts { get; protected set; }
//irrelevant code omitted
}
當我嘗試使用 fluent API 來映射這種多對多關系時,它給我帶來了一些麻煩。 顯然,當我在user.Contacts
屬性上使用HasMany()
時,它沒有WithMany()
方法可以調用 next。 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
那么為什么會發生這種情況呢? 映射這種多對多關系有什么我做錯了嗎?
那么為什么會發生這種情況呢? 映射這種多對多關系有什么我做錯了嗎?
尚不支持沒有實體類來表示連接表的多對多關系。 但是,您可以通過為連接表包含一個實體類並映射兩個單獨的一對多關系來表示多對多關系。
使用 EF-Core,您應該為映射表創建實體。 例如UserContacts
。 文檔中的完整示例,如評論中所述。 我還沒有真正測試過下面的代碼,但它應該是這樣的:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.