.net-corecore-api

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


Here is my Schema and with two Foreign Key in an intermediate table. I am beginner in Core dotnet so unable to crate API to show the department in the school.

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

Here I want to get all department related to school id, how can i get all the department though the School id in dotnetcore API.

Here is the school class entity schema.

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

And more here is the department schema.

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

And I am trying to get a department list in the query in the following controller.

[Route("api/[controller]")]
[ApiController]
public class DepartmentSchoolController : ControllerBase
{
    private readonly learning_gpsContext _learning_GpsContext;
    public DepartmentSchoolController(learning_gpsContext learning_GpsContext)
    {
        _learning_GpsContext = learning_GpsContext;
    }

Solution

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

    For further learning check this tutorial. You should also understand what REST is and for basic questions always take a look at the official documenation.