2012-11-30 92 views
2

我希望能夠訪問的追隨者並遵循從我的用戶實體的集合:映射的Twitter風格的追隨者繼EF代碼第一次關係

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

那麼這將映射到表:

UserFollowers(UserId, FollowerId)

我可以生成的表格正確的追隨者一些流暢的配置工作:

modelBuilder.Entity<User>().HasMany(m => m.Followers).WithMany().Map(x => x.MapLeftKey("UserId").MapRightKey("FollowerId").ToTable("UserFollowers")); 

棘手的部分是讓EF知道以下集合應該映射到同一個表,但跟隨用戶的映射關係映射。

我試圖簡單地增加:

modelBuilder.Entity<User>().HasMany(m => m.Following).WithMany().Map(x => x.MapLeftKey("FollowerId").MapRightKey("UserId").ToTable("UserFollowers")); 

,但我得到一個錯誤:

The EntitySet 'UserUser1' with schema 'dbo' and table 'UserFollowers' was already defined. Each EntitySet must refer to a unique schema and table.

我該如何解決這個問題?

回答

4

你可以使用這樣的映射來做到這一點。

modelBuilder.Entity<User>().HasMany(m => m.Followers).WithMany(m=>m.Following).Map(x => x.MapLeftKey("UserId").MapRightKey("FollowerId").ToTable("UserFollowers"));