Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error:-Object reference not set to an instance of an object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...
 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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading