Basically, I have many companies that can have many offices, how do I get my query to show this, I have:
The problem (or so it seems to me is), I am retrieving a company 3 times (example below), when I should only recieve one company and many offices, is my query just plain wrong?
//companies = _repo.All<Companies>();
//mainoffice = _repo.All<Office>();
var dto = companies
.Join(mainoffice, x => x._ID, y => y.CompanyID, (x, y) => new
{
mycompany = x,
myoffice = y,
})
.Select(x => new
{
ID = x.mycompany._ID,
Offices = x.myoffice
});

However if I do a group join, I get what I want but I am getting back companies that dont have offices…
var dto = companies
.GroupJoin(mainoffice, x => x._ID, y => y.CompanyID, (x, y) => new
{
mycompany = x,
myoffice = y,
})
.Select(x => new
{
ID = x.mycompany._ID,
Offices = x.myoffice
});
Update: 1 more nested result set…
var areascovered = repo.All<OfficePostCode>();
var filter = repo.All<PostCodeDistrict>()
.Where(x => x.Region.StartsWith(postcode))
.Join(areascovered, x => x.PostCodeID, y => y.PostCodeID, (x, y) =>
new
{
Postcode = x.PostCode,
Region = x.Region,
OfficeID = y.OfficeID
});
var mainoffice = repo.All<Office>();
var dto = companies
.Select(company => new
{
ID = company._ID,
Offices = mainoffice.Select(office => new
{
CompanyID = office.CompanyID,
Name = office.Name,
Tel = office.Tel,
RegionsCovered = filter.Where(f => f.OfficeID == office.OfficeID)
})
.Where(y => y.CompanyID == company._ID)// && y.RegionsCovered.Any())
})
.Where(pair => pair.Offices.Any());
You don’t need a join, you just need a nested select. Try something like this instead:
If you don’t want entries with companies without offices then try this one:
Explicit lambda version (dot notation):
First one:
Companies without offices, removed: