基本上,我有很多公司可以有很多办公室,如何让我的查询显示这个,我有: 问题(或者在我看来是这样),我正在检索一家公司3次(例如下面的例子),当我只收到一家公司和许多办公室时,我的查询是否完全错误?
//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
});
然而,如果我加入团体,我会得到我想要的东西但我找回那些没有办公室的公司......
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
});
更新:另外1个嵌套结果集......
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());
答案 0 :(得分:0)
您不需要加入,只需要嵌套选择。尝试这样的事情:
from company in companies
select new
{
ID = company._ID,
Offices = mainoffice.Where(office => office.CompanyID == company._ID)
}
如果您不希望公司没有办公室的条目,那么试试这个:
from company in companies
let offices = mainoffice.Where(office => office.CompanyID == company._ID)
where offices.Any()
select new
{
ID = company._ID,
Offices = offices
}
显式lambda版本(点表示法):
第一个:
companies.Select(company => new
{
ID = company._ID,
Offices = mainoffice.Where(office => office.CompanyID == company._ID)
});
没有办事处的公司,已删除:
companies.Select(company => new
{
ID = company._ID,
Offices = mainoffice.Where(office => office.CompanyID == company._ID)
})
.Where(pair => pair.Offices.Any());
答案 1 :(得分:0)
没有必要和办公室一起加入公司,在这样的加入中你会看到每家公司都有办公室的数量,我想你可以尝试下面的说法:
companies.SelectMany(x=>x.Offices).Select(x=>new {ID = x.CompanyID, Office = x})
或
offices.GroupBy(x=>x.CompanyID).Select( x=>new {ID = Key, Offices = x});
我假设你在每个办公室都有公司ID。
如果您还想拥有完整的公司,请执行cxan
var officeGroups =
offices.GroupBy(x=>x.CompanyID).Select( x=>new {ID = Key, Offices = x});
var result = from c in companies
join o in officeGroups on c.ID equals o.ID
select new {Company = c, Offices = o.Offices};