将2个用户相互关联

时间:2016-05-10 07:30:34

标签: asp.net-mvc asp.net-mvc-5 asp.net-identity

尝试创建一个可以将2个应用程序用户连接在一起的类,但迁移会在混合中添加额外的用户ID,这让我觉得我做错了,

public class UserReview
{
    [Key]
    [Column(Order = 5)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Column(Order = 10)]
    [ForeignKey("ApplicationUserReviewer")]
    public string ReviewerUserId { get; set; }
    public virtual ApplicationUser ApplicationUserReviewer { get; set; }

    [Column(Order = 15)]
    [ForeignKey("ApplicationUserReviewed")]
    public string ReviewedUserId { get; set; }
    public virtual ApplicationUser ApplicationUserReviewed { get; set; } 
/*few more fields*/

}

在我添加的应用程序用户中

public virtual ICollection<UserReview> UserReviews { get; set; }

在ApplicationDbContext中添加了

public DbSet<UserReview> UserReviews { get; set; }

迁移在这个意义上产生了一些东西,最后有额外的用户ID

ID = c.Int(nullable: false, identity: true),
                        ReviewerUserId = c.String(maxLength: 128),
                        ReviewedUserId = c.String(maxLength: 128),
/*....*/
                        ApplicationUser_Id = c.String(maxLength: 128),

任何解决此事的建议,

此外,我尝试使用UserId和applicationuser_id为第一个用户ID仍尝试添加第3个引用。

1 个答案:

答案 0 :(得分:4)

问题是你在User和UserReview之间有2个连接,所以当你创建UserReviews的集合时,实体框架并不真正知道你想要使用哪个连接。要配置此类事物,您应该在DBContext类上使用FluentAPI进行配置。看看这个答案Entity Framework Code First - two Foreign Keys from same table

做这样的事情:

modelBuilder.Entity<UserReview>()
                .HasRequired(m => m.ApplicationUserReviewer)
                .WithMany(t => t.UserReviews)
                .HasForeignKey(m => m.ApplicationUserReviewerId);
相关问题