首页 > 解决方案 > 需要基于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;
    }

标签: .net-corecore-api

解决方案


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

如需进一步学习,请查看本教程。您还应该了解什么是 REST,对于基本问题,请务必查看官方文档


推荐阅读