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.