首页 > 解决方案 > EF中的一对多关系

问题描述

我有以下问题:事实证明,当我从数据库中编写文章表的控制器时,我的网页上出现错误。我将 ASP.NET Core 5 与预先存在的数据库一起使用。我是这方面的新手,我正在通过创建项目来学习。

在我的控制器类中,我有这个: https ://codeshare.io/3AoPBB

我有这门课articlesviewmodelhttps ://codeshare.io/mp08vk

这是我的articlemaphttps ://codeshare.io/0gQqZv

DbContextSytemhttps ://codeshare.io/1YD6Bj

ArticleSQL Server 数据库中的表: https ://codeshare.io/DZrPJk

CategorySQL Server 中表的类:

public class Category
{
    public int idcategory { get; set; }
    [Required]
    [StringLength(50, MinimumLength = 3, ErrorMessage = "The Category must not have more than 50 characters")]
    public string namecategory { get; set; }
    public string descategory { get; set; }
    public bool numberstatate { get; set; }

    // modify table category
    public ICollection<Article> articles { get; set; }
}

我真的不知道我在包含中做错了什么

标签: asp.net-web-apiasp.net-core-5.0

解决方案


我用下面的方法解决了,原来是因为category和articles表之间缺少外键导致报错,我在dbcontextsystem下用下面这行代码解决了modelBuilder.ApplyConfiguration(new ArticleMap());

modelBuilder.Entity<Article>().HasOne(a => a.Category).WithMany(c => c.articles).HasForeignKey(a => a.idcategory);

推荐阅读