Reputation: 99
I have a many to many relationship between Company and CompanyType
I want to get a list for a dropdown of only Companies with a CompanyType.Name of "Client". I.e. a clientCompanyList.
How can I do that in linq?
I basically wanted to do the following but in 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();
Upvotes: 0
Views: 22
Reputation: 680
You can use include statement, if it having proper foreign key relation ships between tables
var clientCompanies = db.CompanyTypes
.Where(ct => ct.Name == "Client").Include(ct => ct.CompanyTypeCompanies).Include(ct => ct.Companies).Select(ct => ct.Companies).ToList();
In startup class
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}
Upvotes: 1