So I am stuck again...
I have three tables that I am trying to join and group with linq; Company, Notices and Requests.
A company could have many notices.
A notice have a SubcategoryId and a CompanyId
A request have a SubcategoryId.
My aim here is to get a list of companies and for each company get a list of their noticed subcategories and for each noticed subcategory the requests within that subcategory
Ex: Company x is monitoring the subcategories 4 and 7. Show him what requests we've got within those subcats.
This is how I do it for only one company. But I can't solve the grouping and joins when I need a list of multiple companies.
Company company = db.Companies.Where(x=>x.UserId == 10).FirstOrDefault();
var requestByNotices =
from notice in company.Notices
join request in db.Requests.Where(z => z.IsApproved &
z.Status.Status == "Active") on notice.SubcategoryId equals
request.Subcategoryid
UPDATE
Let me rephrase my questions.
This query is producing a table with the results I am looking for:
SELECT Companies.CompanyId, Companies.Name, Account.Email, Notices.SubcategoryId, Requests.FriendlyName FROM Companies
INNER JOIN Notices ON Companies.CompanyId = Notices.CompanyId
INNER JOIN Account ON Account.UserId = Companies.Uid
INNER JOIN Requests ON Notices.SubcategoryId = Requests.Subcategoryid
WHERE Requests.StartDate > '2013-12-22';
But instead of generating a flat list I would like to translate this into to linq but also group by CompanyId. So each company is represented by one row only and within that company I can get the requests.
So instead of a list like this:
CompanyId Name Email SubcategoryId FriendlyName
1 Test test@test.com 2 x
1 Test test@test.com 4 y
I would like to have it like this:
CompanyId Name Email GroupOfRequests
1 Test test@test.com contains two
Thankful for any help!
UPDATED: if i understand right you want something like this
var result =
from company in db.Companies
from notice in company.Notices
join request in db.Requests.Where(z => z.IsApproved &&
z.Status.Status == "Active") on notice.SubcategoryId equals request.Subcategoryid
group new {notice, request } by company into gr
select new {gr.Key, Value = gr.ToList() }
UPDATE2
for your sql it seems like this
from company in db.Companies
join notice in db.Notices on company.CompanyId equals notice.CompanyId
join account in db.Account on company.Uid equals account.UserId
join request in db.Requests on notice.SubcategoryId equals request.SubcategoryId
group new {notice, request} by new {company, account} into g
select new {g.Key, value = g}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.