[英].NET Core use AppUser as attribute in another model
So what I'm trying to do is associate an author with a post.所以我要做的是将作者与帖子相关联。 The class AppUser extends from IdentityUser.
AppUser 类从 IdentityUser 扩展而来。 I'm trying to set the author of each post as an AppUser, but I'm having some problems.
我试图将每篇文章的作者设置为 AppUser,但我遇到了一些问题。 In the database Author doesn't show up instead it's AuthorId, why is that?
在数据库中,作者没有出现,而是 AuthorId,这是为什么? However it seems looks lika i can reach the AppUser from the post, I get no error or warnings.
但是看起来我可以从帖子中访问 AppUser,我没有收到错误或警告。 But i Still can't view the author name with help of the post, can someone please explain why?
但是我仍然无法在帖子的帮助下查看作者姓名,有人可以解释原因吗?
Post Model岗位模型
public class Post
{
.....
.....
public AppUser Author { get; set; }
}
AppUser应用用户
public class AppUser : IdentityUser
{
}
Controller控制器
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Post post)
{
if (ModelState.IsValid)
{
AppUser appUser = await userManager.GetUserAsync(HttpContext.User);
post.Author = appUser;
string slug = userProject.Name.ToLower().Replace(" ", "-");
post.Slug = slug;
context.Add(post);
await context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(post);
}
View看法
This is how I'm trying to print the author name in a view, however it just leaves the space empty, I can show all the other attributes of the model in the same way.这就是我试图在视图中打印作者姓名的方式,但是它只是将空间留空,我可以以相同的方式显示模型的所有其他属性。
@Html.DisplayFor(modelItem => item.Author.UserName)
Why won't the author UserName show and why will the attribute show up at AuthorId instead of author?为什么不显示作者用户名,为什么属性会显示在 AuthorId 而不是作者?
Thanks!谢谢!
Edit - added index action编辑 - 添加索引操作
public IActionResult Index()
{
var posts= context.Posts;
return View(posts);
}
You should add AuthorId
to your Post
model.您应该将
AuthorId
添加到您的Post
模型。
public class Post
{
public string AuthorId { get; set; }
[ForeignKey("AuthorId")]
public AppUser Author { get; set; }
}
and just set AuthorId
to appUser.Id
并将
AuthorId
设置为appUser.Id
post.AuthorId = appUser.Id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.