-2

I actually wanted to save data to my relational database. But I have fallen down a strange problem when i trying to add the data into database. I don't understand why I found this issue. Here is the code:-

Class model:-

 public class AppUser : IdentityUser<int>
    {
       [JsonIgnore]
       public List<QuestionPost> Qpost { get; set; }
       [JsonIgnore]
       public List<Comment> Comments { get; set; }
    }

 public class QuestionPost
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int? UserId { get; set; }
        public AppUser User { get; set; }
        public List<Comment> Comments { get; set; }
    }

 public class Comment
    {
        public int Id { get; set; }
        public string Content { get; set; }
        public int? UserId { get; set; }
        public AppUser User { get; set; }
        public int? PostId { get; set; }
        public QuestionPost Qpost { get; set; }
    }

Datacontext.cs

...
 builder.Entity<AppUser>()
            .HasMany(u => u.Qpost)
            .WithOne(p => p.User)
            .HasForeignKey(p => p.UserId);

        builder.Entity<AppUser>()
            .HasMany(u => u.Comments)
            .WithOne(c => c.User)
            .HasForeignKey(c => c.UserId);

        builder.Entity<QuestionPost>()
            .HasMany(p => p.Comments)
            .WithOne(c => c.Qpost)
            .HasForeignKey(c => c.PostId);

and there is my controller class:-

        [HttpPost("addq")]
        public async Task<IActionResult> CreateComment( [FromBody]Comment comment)
        {
            var qpost = await _context.QuestionPosts
                .FirstOrDefaultAsync(p => p.Id == comment.PostId);

            var UserId = int.Parse(User.GetUserId());
            
            var user = await _context.Users
                .FirstOrDefaultAsync(u => u.Id == UserId);
           
            if (qpost != null && user != null)
            {
                comment.Qpost = qpost;
                comment.User = user;
                qpost.Comments.Add(comment); //here i found null exceptioin but it's not!
                user.Comments.Add(comment);
               
            }
            await _context.SaveChangesAsync();
            return Ok();
        }

in this line: qpost.Comments.Add(comment); i found the actual problem. it should work but i don't understand why i found this kind of unexpected null exception. My comment parameter is contain:-

{
    "content": "This is a comment",
    "postId": 1
}

It should work dafinately, I don't understand how to solve this annoying problem. I am an absolute beginner please help.

  • "It should work dafinately" - I would strongly encourage you to *start* with an expectation that the bug is in your code (as it appears to be in this case). Starting with an assumption that your current code should definitely work, and that therefore the fault lies elsewhere, is likely to make it much harder for you to find issues. – Jon Skeet Jan 30 '23 at 14:07

1 Answers1

2

You need to include the comments when you retrieve QuestionPosts from database, otherwise the navigation property "Comments" will be null.

var qpost = await _context.QuestionPosts
    .Include(qp => qp.Comments)
    .FirstOrDefaultAsync(p => p.Id == comment.PostId);
Neil W
  • 7,670
  • 3
  • 28
  • 41