Search code examples
asp.net-mvcasp.net-mvc-5asp.net-identity

Linking 2 users to each other


Trying to create a class that I can connect 2 applicationusers together, but migration is adding extra userid into the mix making me think im doing this wrong,

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*/

}

In the application user i've added

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

In ApplicationDbContext added

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

Migration generates something in this sense with extra userid at the end

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

any suggestions to get around this,

Also I tried just UserId and applicationuser_id for the first userid still tries to add the 3rd reference.


Solution

  • The problem is that you have 2 connections between User and UserReview, so when you create that collection of UserReviews Entity Framework don't really know which connection you would like to use. To configure such thing you should configure it with FluentAPI on your DBContext class. Look at this answer Entity Framework Code First - two Foreign Keys from same table

    Do something like this:

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