【发布时间】:2023-01-30 22:06:24
【问题描述】:
我实际上想将数据保存到我的关系数据库中。但是当我试图将数据添加到数据库中时,我遇到了一个奇怪的问题。我不明白为什么我会发现这个问题。 这是代码:-
类模型:-
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);
还有我的控制器类:-
[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();
}
在这一行中: qpost.Comments.Add(comment);我发现了实际问题。它应该可以工作,但我不明白为什么我会发现这种意外的空异常。我的comment 参数包含:-
{
"content": "This is a comment",
"postId": 1
}
它应该可以正常工作,我不明白如何解决这个烦人的问题。我是一个绝对的初学者,请帮忙。
【问题讨论】:
-
“它应该能正常工作”——我强烈建议你开始期望错误在您的代码中(在这种情况下似乎是这样)。一开始就假设您当前的代码肯定可以工作,因此错误出在其他地方,这可能会使您更难发现问题。
标签: c# entity-framework asp.net-core asp.net-web-api