I have a simple issue that's running me around, I would like to find out how I can use linq to query a subset of data, e.g. I have a table that contains certificates, certificates belong to a company and a company has users that belong to it and the view is basically supposed to only display certificates for a company whereby the current user is linked to. This is what I currently have and battling with the correct syntax for an exist statement or subquery?
public List<CertificateListItemModel> GetUserCertificates()
{
var certificates = (from p in _db.Certificates
**where(
from bu2 in _db.BusinessUsers
where p.BusinessId == bu2.BusinessId && bu2.Email == _user.Name
//select new {}
)**
select new CertificateListItemModel
{
...
})
.Distinct().ToList();
return certificates;
}
I managed to resolve my issue with a simpler way and it seems it was not that difficult. The above solution confused me and I failed to implement it. Please find the simpler solution below. I just need to add the Where with a bool condition
var applications = (_db.Certificates
.Join(_db.BillingItems, p => p.CertificateId, bi => bi.CertificateId, (p, bi) => new {p, bi})
.Where(@t => (_db.BusinessUsers.Any(c => c.CbrBusinessId == @t.p.CbrOwnerRef && c.Email == _user.Name)))
.Select(@t => new CertificateListItemModel
{
CertificateId = @t.p.CertificateId,
ApplicationRefNo = @t.p.ApplicationReferenceNo,
ApplicationStatus = @t.p.ApplicationStatus,
SubmittedDateTime = @t.p.SubmittedDateTime,
IssuingLocation = @t.p.DesiredIssueLocation,
BillingId = @t.bi.BillingId,
PaperNo = @t.bi.PaperNo,
InvoiceNo = @t.bi.InvoiceNo,
BillingStatus = @t.bi.BillingStatus,
InvoiceRefNo = @t.bi.PaperNo,
BillingParty = @t.bi.BillingParty
}))
.Distinct().ToList();
return applications;