Mike June Bug Captain Mike June Bug Captain - 1 year ago 84
C# Question

EF Core Self Referencing

I want a user to have many followers and many people they are following.

Right now im getting this error.


Unable to determine the relationship represented by navigation property 'ApplicationUser.Following' of type 'ICollection'. Either manually configure the relationship, or ignore this property from the model.


// ApplicationUser File.
public class ApplicationUser : IdentityUser<int>
{
// OTHER PROPERTIES ABOVE
public virtual ICollection<ApplicationUser > Following { get; set; }
public virtual ICollection<ApplicationUser > Followers { get; set; }
}

// Context File
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}

Answer Source

You need an extra class to accomplish that. Something like this should work:

public class ApplicationUser : IdentityUser<int>
{
    public string Id {get; set;}
    // OTHER PROPERTIES ABOVE
    public virtual ICollection<UserToUser> Following { get; set; }
    public virtual ICollection<UserToUser> Followers { get; set; }
}

public class UserToUser 
{
    public ApplicationUser User { get; set;}
    public string UserId { get; set;}
    public ApplicationUser Follower { get; set;}
    public string FollowerId {get; set;}
}

// Context File
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<UserToUser>()
        .HasKey(k => new { k.UserId, k.FollowerId });

    modelBuilder.Entity<UserToUser>()
        .HasOne(l => l.User)
        .WithMany(a => a.Followers)
        .HasForeignKey(l => l.UserId);

    modelBuilder.Entity<UserToUser>()
        .HasOne(l => l.Follower)
        .WithMany(a => a.Following)
        .HasForeignKey(l => l.FollowerId);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download