skip to Main Content

I am trying to create a follow system and so far everything is working fine, however I am trying to add a feature where you can request to follow a user, and it is not getting any kind of requests and returning as null even though I have follow request in my database.

My logic is the following. I have a table with the followersId, followingId and PendingStatus which represent either if the follow request was accepted or not (true = waiting to be accepted, false = accepted).

I will leave some of my models used in my code:

public class AppUser : IdentityUser
{
    public AppUser()
    {
        Follower = new List<FollowUser>();
        Following = new List<FollowUser>();
    } 
    
    public override string Id { get; set; }
    public required string FullName { get; set; }
    
    // Follow system
    public ICollection<FollowUser> Follower { get; set; }
    public ICollection<FollowUser> Following { get; set; }
    
    // Account Settings
    public bool IsPrivate { get; set; } = false;
}
public class FollowUser
{
    public string FollowerId { get; set; }
    public string FollowingId { get; set; }

    public required bool PendingStatus { get; set; }

    [JsonIgnore]
    public AppUser Follower { get; set; }
    [JsonIgnore]
    public AppUser Following { get; set; }
}

This is how my endpoint looks like

[HttpGet("follow-requests/{userId}")]
    public async Task<ActionResult> GetFollowRequests([FromRoute] string userId)
    {
        var user = await _userManager.FindByIdAsync(userId);
    
        if (user == null)
            return BadRequest("Failed to find user with the specific id");
        
        var requests =  await _userManager.Users
            .Where(u => u.Id == userId)
            .SelectMany(u => u.Following)
            .Where(f => f.PendingStatus == true && f.FollowingId == userId)
            .ToListAsync();
        
        if (requests.IsNullOrEmpty())
            return Ok("You don't have any follow requests");
        return Ok(requests);
    }

2

Answers


  1. Chosen as BEST ANSWER

    So, I eventually got it right. What happens is that I wasn't including my Followers which makes it not querying anything from the database. Here is how my query is now:

    var requests = await _dbContext.FollowUsers
                .Include(f => f.Follower)
                .Where(f => f.FollowingId == userId && f.PendingStatus == true)
                .Select(f => f.Follower)
                .ToListAsync();
    

  2. To follow up with your answer Mateus, By default EF Core has Lazy loading enabled. which means that data won’t be loaded until it is requested. Here’s Loading Related Data information regarding EF Core. You will be able to check what other kind of loading strategies exist.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search