I'm currently learning ASP.NET and having some problems. I have 2 tables related to each other by Foreign Key.
Employee.cs
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[Column(TypeName = "nvarchar(50)")]
[Required]
public string EmployeeFullName { get; set; }
[Required]
[ForeignKey("DepartmentId")]
public virtual Department EmployeeDepartment { get; set; }
}
Department.cs
public class Department
{
[Key]
public int DepartmentId { get; set; }
[Column(TypeName = "nvarchar(10)")]
[Required]
public string DepartmentName { get; set; }
}
I use the HTTP POST JSON and normally get values at both tables:
{
"employeeId": 0,
"employeeFullName": "string",
"employeeDepartment": {
"departmentId": 0,
"departmentName": "string"
}
}
But when I use the GET HTTP. I got:
[
{
"employeeId": 1,
"employeeFullName": "string",
"employeeDepartment": null
}
]
How can I show the employeeDepartment as JSON instead. Like this:
[
{
"employeeId": 1,
"employeeFullName": "string",
"employeeDepartment":{
"departmentId":1,
"departmentName":"string"
}
}
]
I use the API Controller
[HttpGet("{id}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
var employee = await _context.Employees.FindAsync(id);
if (employee == null)
{
return NotFound();
}
return employee;
}
How can I use http GET to receive just some specific fields? For example, I just want to get the EmployeeId with EmployeeFullName only.