简体   繁体   中英

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM