我与Company和CompanyType之间有很多关系
我想获取一个列表,其中仅列出CompanyType.Name为“ Client”的公司。即一个clientCompanyList。
如何在linq中做到这一点?
我基本上想在linq中做以下事情
var clientCompanies = db.Companies.SqlQuery(@"SELECT c.*
FROM Companies AS c
JOIN CompanyTypeCompanies AS ctc ON ctc.Company_ID = c.ID
JOIN CompanyTypes AS ct ON ctc.CompanyType_ID = ct.ID
WHERE ct.Name = 'Client'").ToList();
答案 0 :(得分:1)
如果表之间具有正确的外键关系,则可以使用include语句
var clientCompanies = db.CompanyTypes
.Where(ct => ct.Name == "Client").Include(ct => ct.CompanyTypeCompanies).Include(ct => ct.Companies).Select(ct => ct.Companies).ToList();
在启动课程中
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}