//This is student model
namespace StudentApp.Models
{
public class Student
{
[Key]
public int studentId { get; set; }
public List<AssignedSupervisor> assigned_supervisorId { get; set; }
}
public class AssignedSupervisor
{
[Key]
public int supervisorId { get; set; }
}
}
Based on the Student Model, entity framework has created the below db
//Here is the sample db structure
//Table Students
studentId
---------
1
2
//Table Supervisors
supervisorId | studentId
------------ ---------
101 1
102 1
105 2
studentId is a foreign key in Supervisor Table. Students can have one or more supervisors assigned. Required output should be similar to the below example:
{
"studentId": "1",
"supervisorId": [101,102]
},
{
"studentId": "2",
"supervisorId": [105]
}
Below is the DTO
//This is student DTO
namespace StudentApp.DTOs
{
public class StudentDTO
{
public int studentId { get; set; }
public List<AssignedSupervisor> assigned_supervisorId { get; set; }
}
}
In my controller
namespace ContractingApp.Controllers
{
//first way I'm doing which returns ugly JSON.
public List<StudentDTO> GetStudents()
{
return db.Students.Select(s => new StudentDTO()
{
studentId = s.studentId,
//Not sure how to use the select statement with it
assigned_supervisorId = s.Supervisors.Where(
u => u.studentId == s.studentId
).ToList()
}).ToList();
}
//Another way I have tried after the suggestions by @darth_phoenixx I'm trying which doesn't return correct correct format either.
//It returns 3 JSON objects - one with each supervisor ID.
public List<dynamic> GetStudents()
{
var students = (from t1 in db.Students
join t2 in db.Supervisors on t1.studentId equals t2.studentId
select new
{
t1.studentId,
t2.supervisorId
});
return students.ToList<dynamic>();
}
}
Any article or direction to solve will be helpful.