需要在dotnet核心中基于ForeignKey创建API

时间:2019-01-23 06:12:48

标签: .net-core core-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;
    }

1 个答案:

答案 0 :(得分:0)

[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。您还应该了解REST是什么,对于基本问题,请始终查看official documenation