I'm just learning LINQ to SQL and have run into the following obstacle.
I have a the following 3 tables:
- PC (PCGUID, ParentPCGUID, ModelName, RetailerGUID)
- Offer (OfferGUID, ParentGUID, Title)
- Retailer (RetailerGUID, Name)
With the following relationships:
- PC 1:N Offer
- Retailer 1:N PC
- Retailer 1:N Offer
- PC 1:N PC (self referencing)
I need to grab records from PC with only 1 record from PC.Offer (with specific where clauses) and only 1 record from PC.Retailer.Offer (with specific where clauses) and, hopefully, with only one hit on the database.
I have the follow query so far (I've tried about a hundred so far), but it hits the db multiple times.
var q = from pc in PCs
where pc.PCGUID == guid || pc.ParentPCGUID == guid
select new {
PC = pc,
PCOffers = pc.Offers.FirstOrDefault(),
RetailOffers = pc.Retailer.Offers.FirstOrDefault()
};
If I bring only one property of the offer table like so:
var q = from pc in PCs
where pc.PCGUID == guid || pc.ParentPCGUID == guid
select new {
PC = pc,
PCOffers = pc.Offers.FirstOrDefault().Title,
RetailOffers = pc.Retailer.Offers.FirstOrDefault().Title
};
It works just fine and only hits the db once, but I need the whole offer object. Any help would be greatly appreciated.
Thanks