Reputation: 1
I have 3 related entities:
PurchaseOrder
(Id, ProjectId, Source, CompanyId, ...)Company
(Id, Name, ...)Contacts
(Id, CompanyId, Email, AutoEM, ...)Each purchase order has a related company and each company can have one or more contacts where one of them is set as the primary or default contact (eg: AutoEM == true
).
I would like the LINQ to return a set of PurchaseOrder
rows for a selected ProjectId
and include, on each row, the company name its for, and the contact email for the primary contact for that company.
I was able to get the PO and Company info displayed on my page, but have not been able to figure out how to include the primary contact which has AutoEM == true
. Thank you in advance for any help.
pos = context.PurchaseOrder
.Where(p => p.ProjectId == Int32.Parse(id))
.Include(p => p.company)
.ToList();
Upvotes: 0
Views: 65
Reputation: 244
So, you want to include the primary contact which has AutoEM == true.
The condition (where statement) should be applied to the include of Contacts. The use of "ThenInclude" is to guarantee that related Company is added first and then including related Contacts where AutoEM == true.
I suggest the following update to the code:
pos = context.PurchaseOrder
.Where(p => p.ProjectId == Int32.Parse(id))
.Include(p => p.company)
.ThenInclude(p => p.Contacts.Where(c => c.AutoEM == true))
.ToList();
Upvotes: 1