I’m trying to make a Social App like Facebook where you can add people as friends.
Now, I want to add a “People you may know section” in which all application users appears except your friends.
I Made a Model “ApplicationUser” that have a self Many-to-Many relationship so that a user can have multiple friends. Here’s the Definition of “ApplicationUser” Model :
public class ApplicationUser : IdentityUser
{
public string Fullname { get; set; }
public DateOnly BirthDate { get; set; }
public string? ProfilePicUrl { get; set; }
public string Bio { get; set; }
public ICollection<User_Friend> Users { get; set; }
public ICollection<User_Friend> Friends { get; set; }
}
And here’s the Definition of “User_Friend” Model that maps the M-N relation :
public class User_Friend
{
public int Id { get; set; }
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public string FriendId { get; set; }
public ApplicationUser Friend { get; set; }
public DateTime FriendsSince { get; set; }
}
here’s my code , it’s working as expected but it looks like there must be a better or cleaner way
public IActionResult Index()
{
var claim = (ClaimsIdentity)User.Identity;
var user = claim.FindFirst(ClaimTypes.NameIdentifier);
//everyone ids except me
List<string> AllIds = _context.applicationUsers.Where(u => u.Id != user.Value).Select(x=>x.Id).ToList();
// friends ids
List<string> friendsIds = _context.user_Friends.Where(u => u.UserId == user.Value).Select(x=>x.FriendId).ToList();
// non-friends ids
List<string> nonFriendsIds = AllIds.Except(friendsIds).ToList();
List<ApplicationUser> nonFriends = new List<ApplicationUser>();
if (user != null)
{
foreach (var x in nonFriendsIds)
{
nonFriends.Add(_context.applicationUsers.FirstOrDefault(u => u.Id == x));
}
}
return View(nonFriends);
}