一对多关系存在问题

There are a problem with one-to-many relationship

作者和文章之间存在一对多关系

这是我的模型

    public class Authors
{
    [Key]
    public int AuthorId { get; set; }
    public string AuthorName { get; set; }
    public string Picture { get; set; }
    public List<Articles> Articles { get; set; }
}

    public class Articles
{
    [Key]
    public int ArticleId { get; set; }
    public int AuthorId { get; set; }
    public DateTime Date { get; set; }
    public bool Active { get; set; }
    public string Title { get; set; }
    public string Article { get; set; }
    public int Hit { get; set; }
    public Authors Authors { get; set; }
}

和 ArticleCreate 控制器

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> 
ArticleCreate([Bind("ArticleId,AuthorId,Date,Active,Title,Article,Hit")] Articles articles)
    {
        if (ModelState.IsValid)
        {
            _context.Add(articles);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(ArticlesIndex));
        }
        return View(articles);
    }

我在文章 table 中看到一个名为 AuthorsAuthorId 的新列。当我尝试使用 ArticleCreate 控制器添加新文章时,该 AuthorsAuthorId 列为空。 AuthorId 列已存在于文章 table 中,我可以在此处看到 AuthorId 值。当我在 AuthorsAuthorId 中手动添加一个值时,效果很好。但是我不能添加控制器动作..

我会很感激你的帮助..

尝试在 Articles.

中的 AuthorId 字段中添加注释 [ForeignKey("Authors")]

因为你的table被命名为Authors,但是你的外键被命名为AuthorId(注意复数)EF不能自动推断这是您的外键。