.NET Core 使用 AppUser 作为另一个模型中的属性 [英] .NET Core use AppUser as attribute in another model

查看:19
本文介绍了.NET Core 使用 AppUser 作为另一个模型中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我要做的是将作者与帖子相关联.AppUser 类从 IdentityUser 扩展而来.我试图将每篇文章的作者设置为 AppUser,但我遇到了一些问题.在数据库中,作者没有出现,而是 AuthorId,这是为什么?但是看起来我可以从帖子中访问 AppUser,我没有收到错误或警告.但是我在帖子的帮助下仍然无法查看作者姓名,有人可以解释原因吗?

So what I'm trying to do is associate an author with a post. The class AppUser extends from IdentityUser. I'm trying to set the author of each post as an AppUser, but I'm having some problems. In the database Author doesn't show up instead it's AuthorId, why is that? However it seems looks lika i can reach the AppUser from the post, I get no error or warnings. But i Still can't view the author name with help of the post, can someone please explain why?

发布模型

public class Post
{
    .....
    .....

    public AppUser Author { get; set; }

}

应用用户

public class AppUser : IdentityUser
{
}

控制器

    [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);
    }

查看

这就是我试图在视图中打印作者姓名的方式,但是它只是将空间留空,我可以以相同的方式显示模型的所有其他属性.

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)

为什么不显示作者用户名,为什么属性会显示在 AuthorId 而不是作者?

Why won't the author UserName show and why will the attribute show up at AuthorId instead of author?

谢谢!

编辑 - 添加索引操作

    public IActionResult Index()
    {
        var posts= context.Posts;
        return View(posts);
    }

推荐答案

您应该将 AuthorId 添加到您的 Post 模型中.

You should add AuthorId to your Post model.

public class Post
{
    public string AuthorId { get; set; }

    [ForeignKey("AuthorId")]
    public AppUser Author { get; set; }
}

然后将 AuthorId 设置为 appUser.Id

post.AuthorId = appUser.Id;

这篇关于.NET Core 使用 AppUser 作为另一个模型中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆