即使ApplicationUserId不是,ApplicationUser.Username也为null

时间:2019-01-01 15:16:26

标签: c# asp.net asp.net-mvc razor model-view-controller

我目前遇到NullException问题。我在下面的@comment.ApplicationUser.UserName下遇到错误,,但仅当我接受由其他用户而不是上载图片的用户发布的评论时。如果我对同一张图片发表评论,则用户(me)会正确显示用户名。我真的不知道可能是什么问题,因为如果我呼叫@comment.ApplicationUserId,一切都会正常进行发布图像的用户的ID。当我调用@comment.ApplicationUser.UserName时,它不应该自动链接到ApplicationUser对象吗?

出现错误的视图

@foreach (var comment in Model.Comments)
{
    <dd class="font-italic">

       @comment.Body commented by @comment.ApplicationUser.UserName

    </dd>
}

评论模型

public class Comment
{

        public int Id { get; set; }

        public string Body { get; set; }

        public bool ApprovedByUser { get; set; }

        public ApplicationUser ApplicationUser { get; set; }

        public string ApplicationUserId { get; set; }

        public Photo Photo { get; set; }

        public int PhotoId { get; set; }

}

每次我都会在 CommentsController / Create 中创建新注释

    public ActionResult Create([Bind(Include = "Id,Body,ApprovedByUser,ApplicationUserId,PhotoId")] Comment comment, int id)
    {

        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        var currentUser = userManager.FindById(User.Identity.GetUserId());

        comment.PhotoId = id;
        comment.ApplicationUserId = currentUser.Id;

        if (ModelState.IsValid)
        {
            db.Comments.Add(comment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.PhotoId = new SelectList(db.Photos, "Id", "Title", comment.PhotoId);
        return View(comment);
    }

我还有一个自定义的 PhotoCommentsViewModel ,其中包含照片和该照片的评论。

public class PhotoCommentsViewModel
    {
        public Photo Photo { get; set; }
        public IEnumerable<Comment> Comments { get; set; }
    }

我从此处的照片/详细信息/ {id} 控制器中获取了abobe viewModel

public ActionResult Details(int? id)
        {
            var photo = db.Photos.Find(id);
            var comments = db.Comments.Where(s => s.PhotoId == photo.Id);

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var viewModel = new PhotoUserViewModel
            {
                Photo = photo,
                Comments = comments,
            };


            if (viewModel.Photo == null)
            {
                return HttpNotFound();
            }
            return View(viewModel);
        }

2 个答案:

答案 0 :(得分:2)

在这种情况下,您应该使用紧急加载。

 var comments = db.Comments
                .Where(s => s.PhotoId == photo.Id)
                .Include(x =>x.ApplicationUser).ToList();

请参阅this

答案 1 :(得分:2)

在“详细信息”操作中,需要向ApplicationUser加载注释。

var comments = db.Comments.Where(s => s.PhotoId == photo.Id).Include(x => x.ApplicationUser).ToList();

进一步阅读Loading Related Entities