需要在dotnet core的ForeignKey基础上创建一个API

Need to create an API on the basis of ForeignKey in dotnet core

这是我的模式,中间有两个外键 table。我是 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中的学校ID获取所有部门API。

这是学校class实体架构。

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

进一步学习检查this tutorial. You should also understand what REST is and for basic questions always take a look at the official documenation