【问题标题】:There are a problem with one-to-many relationship一对多关系有问题
【发布时间】:2020-10-17 15:28:10
【问题描述】:

作者和文章之间是一对多的关系

这是我的模型

    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);
    }

我在 Articles 表中看到了一个名为 AuthorsAuthorId 的新列。当我尝试使用 ArticleCreate 控制器添加新文章时,该 AuthorsAuthorId 列为空。 AuthorId 列已经存在于 Articles 表中,我可以在这里看到 AuthorId 值。当我在 AuthorsAuthorId 中手动添加一个值时,效果很好。但我无法添加控制器操作..

我会感谢你的帮助..

【问题讨论】:

    标签: sql-server asp.net-mvc .net-core database-design one-to-many


    【解决方案1】:

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

    由于您的表名为 Authors,但您的外键名为 AuthorId(请注意复数形式),EF 无法自动推断这是您的外键。

    【讨论】:

      猜你喜欢
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2012-03-27
      相关资源
      最近更新 更多