[英]How to include the ApplicationUser of an object in ASP.NET Core
I'm trying to make an app just like LinkedIn / Facebook.我正在尝试制作一个类似于 LinkedIn / Facebook 的应用程序。
I have a list of posts and each one has an ApplicationUser
(ASP.NET IdentityUser
).我有一个帖子列表,每个帖子都有一个
ApplicationUser
(ASP.NET IdentityUser
)。
In my PostController
, I want to return the list of posts and include the ApplicationUser
.在我的
PostController
中,我想返回帖子列表并包含ApplicationUser
。
But I don't want every attribute of the user as an object containing a (hashed) password.但我不希望用户的每个属性都作为包含(散列)密码的 object 。
How can I return a post including ApplicationUser
but without the password attribute?如何返回包含
ApplicationUser
但没有密码属性的帖子?
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
: 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
: ApplicationUser
:
public class ApplicationUser : IdentityUser
{
}
You can create a view model which included the required properties, such as below:您可以创建一个包含所需属性的视图 model,如下所示:
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:然后,将 LINQ 语句更改如下:
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:结果如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.