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

查看:109
本文介绍了.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; }

}

AppUser

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)

为什么不显示作者UserName,为什么属性显示在AuthorId而不是author上?

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天全站免登陆