我试图将此LINQ语句转换为Lambda
表达式。
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();
这是我到目前为止所做的:
totalTickets = context.EventParentSponsors
.Join(context.EventSponsors,
parent => parent.EventSponsorId,
sponsor => sponsor.EventSponsorId,
(parent, sponsor) => new { sponsor.InvitationCount })
.Where(o => o.EventParentSponsors.ParentSponsorId).FirstOrDefault();
但我收到此错误
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
我缺少什么?
答案 0 :(得分:2)
试试这个:
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();
答案 1 :(得分:2)
如果您使用LINQPad,它将显示Lambda格式的方法:
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();
您缺少的关键部分在于您的投影。当您使用查询语法时,您基本上都会投影父元素和子元素:
(parent, sponsor) => new { parent = parent, sponsor = sponsor })
这样您就可以完全访问每一方以用于将来的表达。