I want to create an API for retrieving all the Companies with Employees in Json. I've got the problem sort of joining 2 tables. Look at the code:
Tables:
public class Company : BaseEntity
{
public int CompanyId{get;set;}
public string Name{get;set;}
public string Address{get;set;}
public List <Employee> Workers { get; set; }
public Company()
{
Workers = new List<Employee>();
}
}
public class Employee : BaseEntity
{
public int EmployeeId{get;set;}
public string FirstName{get;set;}
public string LastName{get;set;}
public string Email{get;set;}
public int CompanyId { get; set; }
[ForeignKey("CompanyId")]
public Company Company { get; set; }
}
Here is my controller:
[HttpGet]
[Route("/api/companies")]
public async Task<List<Company>> ShowAllCompanies()
{
return await _context.Companies.Include(w=>w.Workers).ToListAsync();;
}
[HttpGet]
[Route("/api/employees")]
public async Task<IActionResult> ShowAllEmployees()
{
var result = await _context.Employees.Include(c=>c.Company).ToListAsync();
return Json(result);
}
When I include each foreign table I get only one object in Json. If I do not include anything - I've got all the list of objects to show.
What is the problem to display all the workers within the company table?