EF CodeFirst AddColumn到自连接关系

时间:2016-08-06 16:03:47

标签: c# entity-framework

所以我使用asp身份 ApplicationUser有FriendRequests,这就是我做的

public class ApplicationUser : IdentityUser
{
     public ApplicationUser()
     {
          FriendRequests = new Collection<ApplicationUser>();
     }

     public virtual ICollection<ApplicationUser> FriendRequests {get; set;}

}

这是我的Fluent Api Mapping

         modelBuilder.Entity<ApplicationUser>()
         .HasMany(x => x.FriendRequests)
         .WithMany()
         .Map(x => 
                {
                    x.MapLeftKey("UserRequestingID");
                    x.MapRightKey("UserBeingRequestedID");
                    x.ToTable("FriendRequests");
                });

这会创建一个表&#34; FriendRequests&#34;有两列&#34; UserRequestingID&#34;和&#34; UserBeingRequestedID&#34;。

我想添加一个额外的列&#34; isIgnored&#34;到这张桌子,我该怎么办? 我可以这样做吗?或者我只是创建一个新类?

先谢谢。

1 个答案:

答案 0 :(得分:1)

仅当联结表不包含除PK之外的其他列时,才支持通过映射的

"buttonTitle" = "MeinButton"; 关系。所以是的,如果你想要包含额外的列,那么你需要创建显式实体并设置2个many-to-many关系。

这样的事情:

型号:

one-to-many

配置:

public class ApplicationUser : IdentityUser
{
    // ...
    public virtual ICollection<FriendRequest> FriendRequests {get; set;}
    public virtual ICollection<FriendRequest> FriendRequested {get; set;}
}

public class FriendRequest
{
    public string UserRequestingID { get; set; }
    public string UserBeingRequestedID { get; set; }
    public bool IsIgnored { get; set; }
    public virtual ApplicationUser UserRequesting { get; set; }
    public virtual ApplicationUser UserBeingRequested { get; set; }
}