Search code examples
c#asp.net-core-mvcasp.net-core-identity

How to add one to many relationship between Individual user accounts in Asp.NET Core


I am creating a mini social media web app and I want to add relationship between individual user accounts, so that I can make them friends. I have added List object to my Identity User inherited User class to store other user accounts as friends. I have successfully added a user account to the list but it disappears after i added another friend. And when i created a separate method to provide a view with list of friends, there is nothing in the list.

Here is my User class,

public class AppUser : IdentityUser
{
    public int Age { get; set; }
    public string Sex { get; set; }
    public string City { get; set; }
    public string Education { get; set; }
    public string Description { get; set; }

    public List<AppUser> Friends { get; set; } = new List<AppUser>();
}

My DbContext class,

public class ApplicationDbContext : IdentityDbContext<AppUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

    public DbSet<AppUser> Users { get; set; }
}

My Controller Class methods for adding relationship,

public async Task<IActionResult> AddFriend(string Id)
    {
        var friend = await userManager.FindByIdAsync(Id);
        var currentUser = await userManager.GetUserAsync(this.User);
        friend.Friends.Add(currentUser);
        currentUser.Friends.Add(friend);
        await userManager.UpdateAsync(currentUser);
        await userManager.UpdateAsync(friend);
        return View("Friends", currentUser.Friends);
    }
    public async Task<IActionResult> Friends()
    {
        var user = await userManager.GetUserAsync(this.User);
        var friends = user.Friends;
        return View(friends);
    }

Solution

  • You should eager load your navigation but you can't do it with usermanager and your must use your DbContext. Try this:

    public async Task<IActionResult> Friends()
    {
        var user = await _context.Users.Include(p=> p.Friends) // Use ApplicationDbContext 
                              .FirstOrDefaultAsync(q=> q.Id == yourId);
        var friends = user.Friends;
        return View(friends);
    }