.net-core - 需要基于dotnet core中的ForeignKey创建API
问题描述
这是我的架构,中间表中有两个外键。我是 Core dotnet 的初学者,所以无法创建 API 来展示学校的部门。
public class DepartmentSchool
{
public int Id { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department{ get; set; }
public int SchoolsId { get; set; }
[ForeignKey("SchoolsId")]
public virtual Schools Schools { get; set; }
在这里,我想获取与学校 ID 相关的所有部门,如何通过 dotnetcore API 中的学校 ID 获取所有部门。
这是学校类实体模式。
public partial class Schools
{
public int ID { get; set; }
public string UicCode { get; set; }
public int SchoolSystemsId { get; set; }
public string BannerUrl { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public int UserID { get; set; }
public int? Status { get; set; }
public DateTime? CreatedAt { get; set; }
public int? CreatedBy { get; set; }
public DateTime UpdatedAt { get; set; }
public int? ModifiedBy { get; set; }
[ForeignKey("SchoolSystemsId")]
public PrivateSchoolSystem PrivateSchoolSystems { get; set; }
这里还有更多部门架构。
public partial class Department
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public int CreatedBy { get; set; }
public int UpdatedBy { get; set; }
public int SchoolSystemsID { get; set; }
[ForeignKey("SchoolSystemsID")]
public virtual PrivateSchoolSystem PrivateSchoolSystems { get; set; }
我正在尝试在以下控制器的查询中获取部门列表。
[Route("api/[controller]")]
[ApiController]
public class DepartmentSchoolController : ControllerBase
{
private readonly learning_gpsContext _learning_GpsContext;
public DepartmentSchoolController(learning_gpsContext learning_GpsContext)
{
_learning_GpsContext = learning_GpsContext;
}
解决方案
[HttpGet("school/{schoolId}/departments")]
public IActionResult GetDepartmentsFromSchool(int schoolId)
{
var school = _learning_GpsContext.Schools.Where(e=>e.Id == schoolId).FirstOrDefault();
if (school == null)
return NotFound();
var departments = _learning_GpsContext.DepartmentSchool
.Where(e=>e.SchoolsId == schoolId).Select(e=>e.Department);
return Ok(departments);
}
推荐阅读
- msal - 使用 MSAL 访问令牌/刷新令牌
- javascript - ExtJS 我可以在同一个组件中使用 IF 语句吗
- java - 在 Eclipse 中更改 if() 和 { 之间的空格
- javascript - 点击时不计入索引
- r - 如何在 r ggplot2 的多面图上将数据的平均值添加为水平线
- python - 如何忽略错误而不是返回 400 Bad Request?- Django Rest Framework
- android - Android工作室,BottomNavigationView
- mysql - 从同一个表创建 MySQL JOIN (parent_title from parent_id)
- python - 使用 Keras 训练句子序列
- windows - 网络用户 $userName /domain