mysqlasp.netlinqsystemsocial-network-friendship

ASP.NETCore - Friends System


I`m building an application where I try to make a friend system.

Now, I work with 2 tables for that. 1st: Default AspNetUsers where i store user information.

2nd: Friends Table as below:

    public class AspNetFriends
{
    public int ID { get; set; }
    public string friendFrom { get; set; }
    public string friendTo { get; set; }
    public bool isConfirmed { get; set; }
}

In this table both "friendFrom" and "friendTo" is string type, and receiving the registered users ID.

What i want to achieve is that when i display this table on my view, i want to show the Username of the same UserID thats either in the "friendFrom" or "friendTo" column.


Solution

  • You need to change your class as followed (I didn't test this):

    Default application user of asp.net core

    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    
    namespace project.Models
    {
        // Add profile data for application users by adding properties to the ApplicationUser class
        public class ApplicationUser : IdentityUser
        {
    
        }
    }
    

    Model

    public class AspNetFriends
    {
        public int ID { get; set; }
        public bool isConfirmed { get; set; }
        public virtual ApplicationUser friendFrom { get; set; }
        public virtual ApplicationUser friendTo { get; set; }
    }
    

    Now you can get to the getters and setters of the aspnet user

    Controller

    public async Task<IActionResult> Details(int id)
    {
        var query = from m in _dbContext.AspNetFriends
                        join ff in _dbContext.Users on
                            new { m.friendFrom.Id } equals new { Id = cu.Id }
                        join ft in _dbContext.Users on
                            new { m.friendTo.Id } equals new { Id = cu.Id }
                            where m.ID == id
                            select m;
    
        return View(query.Single());
     }
    

    View

    @model project.AspNetFriends
    
    <p>
    @model.friendFrom.UserName
    </P>
    

    @item.CreationUser.UserName