2016-06-18 10 views
0

私は1つのエンティティを持っており、2つの多対多リレーションシップを作成したいと考えています。私のエンティティは次のとおりです。EFコードFirst - Fluent API - Many To Manyリレーションシップ - テーブルを作成しない

public class User : IdentityUser 
{ 
    private ICollection<User> users; 
    private ICollection<User> followers; 
    private ICollection<User> followings; 

    public User() 
    { 
     this.Users = new HashSet<User>(); 
     this.Followers = new HashSet<User>(); 
     this.Followings = new HashSet<User>(); 
    } 

    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    public virtual ICollection<User> Users 
    { 
     get { return this.users; } 
     set { this.users = value; } 
    } 

    public virtual ICollection<User> Followers 
    { 
     get { return this.followers; } 
     set { this.followers = value; } 
    } 

    public virtual ICollection<User> Followings 
    { 
     get { return this.followings; } 
     set { this.followings = value; } 
    } 
} 

マイコンフィギュレーション・クラスは次のようになります。

public class UserMap : EntityTypeConfiguration<User> 
{ 
    public UserMap() 
    { 
     Property(u => u.FirstName).HasMaxLength(50).IsRequired(); 
     Property(u => u.LastName).HasMaxLength(50).IsRequired(); 

     HasMany<User>(u => u.Users).WithMany(f => f.Followers).Map(m => 
     { 
      m.ToTable("UserFollower"); 
      m.MapLeftKey("UserId"); 
      m.MapRightKey("FollowerId");     
     }); 
     HasMany<User>(u => u.Users).WithMany(f => f.Followings).Map(m => 
     { 
      m.ToTable("UserFollowing"); 
      m.MapLeftKey("UserId"); 
      m.MapRightKey("FollowingId"); 
     }); 
    } 
} 

このコードは、一つだけのテーブルUserFollowingの代わりに、二つのテーブルUserFollowingUserFollowerを作成します。テーブルの場所を入れ替えたら、UserFollowerしか得られません。 2番目のテーブルが最初のテーブルを上書きするようです。私は移行とデータベースを削除しようとしましたが、私はまだ同じ結果を得ています。

なぜ誰が起こっているのでしょうか?

+0

UserMapのコンストラクタには、FollowersまたはFollowingsを作成するかどうかを示すパラメータが必要です。ユーザーマップは現在フォロワーを作成しており、オブジェクトをフォローイングで上書きしています。 – jdweng

答えて

1

ここで問題になっているのは、同じナビゲーションプロパティ - ユーザーに対して2つのM:Nマッピングを作成しようとしていることです。あなたが実際に達成しようとしていることについては、実際にはそれを行う必要はありません。どのユーザーがそれに従っているかをマッピングするには、1つのマッピングテーブルのみが必要です。

はこのようにそれを設定してみてください:今すぐ

HasMany<User>(u => u.Following).WithMany(f => f.Followers).Map(m => 
    { 
     m.ToTable("UserFollowing"); 
     m.MapLeftKey("UserId"); 
     m.MapRightKey("FollowingId");     
    }); 

は、あなたはそれらを以下だ人を見つけるために、彼らがフォローしている人を見つけるために、ユーザーで次のようにアクセスし、フォロワーことができます。

少なくともデータアクセスの目的では、実際にはUsersプロパティは必要ないと思われます。両方を組み合わせたリストが必要な場合は、取得専用のプロパティを使用して、[フォロワー]コレクションと[フォロワー]コレクションの結合を返すことができます。