.NET Core use AppUser as attribute in another model

筅森魡賤 提交于 2020-02-06 07:30:34

问题


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?

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?

Thanks!

Edit - added index action

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

回答1:


You should add AuthorId to your Post model.

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

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

and just set AuthorId to appUser.Id

post.AuthorId = appUser.Id;


来源:https://stackoverflow.com/questions/59677923/net-core-use-appuser-as-attribute-in-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!