有:
输入参数CompanyName
。
API /搜索/公司的companyName =柏&安培;页= 1&安培;限制= 20
任务:在Companies
之前获取CompanyName
,在每个Industry
中获取Company
:
查询:
var query = (from company in _context.Companies
where company.Name.Contains(model.Model.CompanyName.Trim())
join ci in _context.CompanyIndustries on company.Id equals ci.CompanyId
join industry in _context.Industries on ci.IndustryId equals industry.Id
select new SearchCompanyModel()
{
Id = company.Id,
Name = company.Name,
Logo = company.LogoUrl,
Industry = industry.Name
})
.GroupBy(x => new {x.Id, x.Name, x.Logo})
.Select(x => new SearchCompanyModel
{
Id = x.Key.Id,
Name = x.Key.Name,
Logo = x.Key.Logo,
Industry = x.FirstOrDefault().Industry
});
答案 0 :(得分:1)
您可以使用加入
void Main()
{
var allCompanies = new Company[] {
new Company{Id = "1", Name = "c1"},
new Company{Id = "2", Name = "c2"},
new Company{Id = "3", Name = "c2"}
};
var allIndustries = new Industry[] {
new Industry{Id = "1", Name = "i1"},
new Industry{Id = "2", Name = "i2"},
new Industry{Id = "3", Name = "i3"}
};
var allCompanyIndustries = new CompanyIndustry[] {
new CompanyIndustry{CompanyId = "1", IndustryId = "1"},
new CompanyIndustry{CompanyId = "1", IndustryId = "2"},
new CompanyIndustry{CompanyId = "3", IndustryId = "1"}
};
var companyName = "c1";
var companies = allCompanies
.Where(company => company.Name == companyName)
.Join(allCompanyIndustries, c => c.Id, ci => ci.CompanyId, (c, i) => new {Company = c, IndustryId = i.IndustryId})
.Join(allIndustries, ci => ci.IndustryId, i => i.Id, (ci, i) => new {Company = ci.Company, Industry = i})
.ToArray();
}
class Company {
public string Id {get;set;}
public string Name {get;set;}
}
class Industry {
public string Id {get;set;}
public string Name {get;set;}
}
class CompanyIndustry {
public string CompanyId {get;set;}
public string IndustryId {get;set;}
}
答案 1 :(得分:1)
您可以尝试多种优化,但如果使用非映射对象类型的属性(即model.Model.CompanyName.Trim()),则可能会阻止查询被缓存(请参阅{{3 }})
幸运的是,这很容易修复,只需将值缓存在查询之外的局部变量中,然后使用此值
var companyName = model.Model.CompanyName.Trim();
这可能会有所帮助,但我提供链接的文章还包含许多其他建议。