asp.net-web-api - EF中的一对多关系
问题描述
我有以下问题:事实证明,当我从数据库中编写文章表的控制器时,我的网页上出现错误。我将 ASP.NET Core 5 与预先存在的数据库一起使用。我是这方面的新手,我正在通过创建项目来学习。
在我的控制器类中,我有这个: https ://codeshare.io/3AoPBB
我有这门课articlesviewmodel
:
https ://codeshare.io/mp08vk
这是我的articlemap
:
https ://codeshare.io/0gQqZv
DbContextSytem
:https ://codeshare.io/1YD6Bj
Article
SQL Server 数据库中的表:
https ://codeshare.io/DZrPJk
Category
SQL 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; }
}
我真的不知道我在包含中做错了什么
解决方案
我用下面的方法解决了,原来是因为category和articles表之间缺少外键导致报错,我在dbcontextsystem下用下面这行代码解决了modelBuilder.ApplyConfiguration(new ArticleMap());
modelBuilder.Entity<Article>().HasOne(a => a.Category).WithMany(c => c.articles).HasForeignKey(a => a.idcategory);
推荐阅读
- powerapps - 在 powerapps 中加载问题
- vuejs2 - vueresource 等待上一个http请求完成后再执行下一个请求
- python - 使用 Tensorflow / Keras 的神经网络中的负二项式损失
- bash - 使用jq通过变量获取json字段值
- visual-studio-code - VSCode xdebug 路径映射
- c++ - gtest 期望无序元素带有自定义比较器/匹配器
- linux - scp 进入 linux 机器时失去连接
- jquery - 复选框验证中的 Jquery 验证错误消息
- karate - 空手道网的能力
- vue.js - Nuxt 生成致命错误:在堆限制附近的无效标记压缩分配失败 - JavaScript 堆内存不足