0

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.

With Include(w=>w.Workers) With Include(w=>w.Workers)

WITHOUT Include(w=>w.Workers WITHOUT Include(w=>w.Workers)

What is the problem to display all the workers within the company table?

Nash
  • 65
  • 5
  • It's not clear what's the problem here. What do you want to happen that's not happening? – Camilo Terevinto Mar 08 '18 at 22:31
  • @CamiloTerevinto I want to return an array of objects like on the second screenshot, but having access to all of the workers in the same time. – Nash Mar 09 '18 at 13:47

1 Answers1

0

You need the "Include()" to eager load. See here for a similar question: Entity Framework - Is there a way to automatically eager-load child entities without Include()?