2016-09-29 16 views
7

多対多リレーションシップを同じエンティティにマップしようとしています。私は、多くの関係に、この多くをマッピングするために流暢なAPIを使用しようとすると、それは私にいくつかのトラブルを与えるエンティティフレームワークコア:同じエンティティと多対多の関係

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

Userエンティティは、ユーザーの連絡先/友人の情報を格納するContactsためIList<User>データフィールドを、持っています。どうやら、をuser.Contactsのプロパティに使用すると、次に呼び出す方法は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

あなたはこれを見てとることがあります。最初のmodelBulder.Entityでhttps://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many –

答えて

15

これはどうしてですか?私がこれをマップするのに間違ったことは何ですか? 多対多の関係ですか?

いいえ、間違ったことはありませんでした。 It's just not supported。現在のステータスhere

結合テーブルを表すエンティティクラスのない多対多の関係は、まだサポートされていません。ただし、 多対多リレーションシップは、結合テーブル のエンティティクラスを組み込み、2つの別個の1対多リレーションシップをマッピングすることで表すことができます。

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

、それがあるべき「.WithMany(p => p.Contacts)」の代わりに.WithMany(p => p.Users) –

+0

@CarlosAdrián - そうは思わない。それ以来、同じテーブルへの参照。まだ複数の連絡先を持つユーザーです。連絡先は依然としてユーザーです。 – smoksnes