Home > Enterprise >  How to include the ApplicationUser of an object in ASP.NET Core
How to include the ApplicationUser of an object in ASP.NET Core

Time:11-25

I'm trying to make an app just like LinkedIn / Facebook.

I have a list of posts and each one has an ApplicationUser (ASP.NET IdentityUser).

In my PostController, I want to return the list of posts and include the ApplicationUser.

But I don't want every attribute of the user as an object containing a (hashed) password.

How can I return a post including ApplicationUser but without the password attribute?

Post.cs

public class Post
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string ApplicationUserID { get; set; }
    [MaxLength(500)]
    public string Contents { get; set; }
    [Required]
    public ulong Timestamp { get; set; }
}

PostController:

[Authorize]
[HttpGet("{id}")]
public async Task<ActionResult<Post>> GetPost(int id)
{
    var post = await _context.Posts
                             .Include(x=> x.ApplicationUser)
                             .FirstOrDefaultAsync(x => x.Id == id);

    if (post == null)
    {
        return NotFound();
    }

    return post;
}

ApplicationUser:

public class ApplicationUser : IdentityUser
{
}

CodePudding user response:

You can create a view model which included the required properties, such as below:

public class PostViewModel
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string ApplicationUserID { get; set; }
    [MaxLength(500)]
    public string Contents { get; set; }
    [Required]
    public ulong Timestamp { get; set; }

    public string UserName { get; set; } //Directly add the username property, used to store the user name

    public UserViewModel User { get; set; } //create a new view model which contains the username
}

public class UserViewModel
{
    public string UserName { get; set; }
}

Then, change the LINQ statement as as below:

var query = _dbcontext.Posts.Include(c => c.ApplicationUser)
               .Select(c => new PostViewModel()
               {
                   Id = c.Id,
                   Contents = c.Contents,
                   Timestamp = c.Timestamp,
                   UserName = c.ApplicationUser.UserName,
                   User = new UserViewModel()
                   {
                       UserName = c.ApplicationUser.UserName
                   } 
               }).ToList();

The result as below:

enter image description here

  • Related