Reputation: 7490
I'm trying to convert this LINQ statement into a Lambda
expression.
totalTickets = (from parent in context.EventParentSponsors
join sponsor in context.EventSponsors
on parent.EventSponsorId equals sponsor.EventSponsorId
where parent.ParentSponsorID == parentId
select sponsor.InvitationCount).FirstOrDefault();
This is what I have so far:
totalTickets = context.EventParentSponsors
.Join(context.EventSponsors,
parent => parent.EventSponsorId,
sponsor => sponsor.EventSponsorId,
(parent, sponsor) => new { sponsor.InvitationCount })
.Where(o => o.EventParentSponsors.ParentSponsorId).FirstOrDefault();
but I get this error
AnonymousType#1' does not contain a definition for 'EventParentSponsors'
and no extension method 'EventParentSponsors' accepting a first argument of type 'AnonymousType#1' could be found
What I am missing?
Upvotes: 0
Views: 2334
Reputation: 33071
If you use LINQPad it will sort of show you what the method looks like in Lambda form:
totalTickets = context.EventParentSponsors
.Join(context.EventSponsors,
parent => parent.EventSponsorId,
sponsor => sponsor.EventSponsorId,
(parent, sponsor) => new { parent = parent, sponsor = sponsor })
.Where(o => o.parent.EventParentSponsors.ParentSponsorId == parentId)
.Select(o => o.sponsor.InvitationCount)
.FirstOrDefault();
The key part you were missing is in your projection. When you use the query syntax, you are basically projecting both the parent and child elements:
(parent, sponsor) => new { parent = parent, sponsor = sponsor })
This is so you have full access to each side for future expressions.
Upvotes: 2
Reputation: 53958
Try this one:
totalTickets = context.EventParentSponsors.Join(context.EventSponsors,
x=>x.EventSponsorId,
y=>y.EventSponsorId,
(x,y) =>
new
{
ID=x.ParentSponsorID ,
Count = x.InvitationCount
})
.Where(x=>x.ID==parentId)
.Select(x=>x.Count)
.FirstOrDefault();
Upvotes: 2