如何将此sql转换为linq查询?

时间:2011-11-04 21:01:48

标签: c# linq linq-to-sql

如何将以下查询转换为linq to sql query?

    select 
invoice.id, web_users.id, web_users.first_name, web_users.last_name,web_users.email_address 
from attendees,web_users
join invoice where attendees.invoice_id=invoice.id and invoice.seminar_id=6 and attendees.web_user_id=web_users.id

这就是我所拥有的,但却引发了一个错误:

from att in context.Attendees
                          from webUsers in context.WebUsers
                          join invoice in context.Invoice
                          on att.InvoiceID equals invoice.ID                          
                          where invoice.SeminarID == seminarId &&
                          webUsers.ID == att.WebUserID                                       
                          select new
                          {
                              webUsers.FirstName,
                              att.InvoiceID                                                       
                          };

提前致谢。

2 个答案:

答案 0 :(得分:1)

尝试:

from att in context.Attendees
                          join webUsers in context.WebUsers
on att.web_user_id equals webUsers.id
                          join invoice in context.Invoice
                          on att.InvoiceID equals invoice.ID                          
                          where invoice.SeminarID == seminarId                                       
                          select new
                          {
                              webUsers.FirstName,
                              att.InvoiceID                                                       
                          };

答案 1 :(得分:1)

首先清理SQL。不要在查询中混合连接和隐式连接,对两者使用显式连接:

select invoice.id, web_users.id, web_users.first_name, web_users.last_name,web_users.email_address 
from attendees
inner join web_users on web_users.id = attendees.web_user_id
inner join invoice on invoice.id = attendees.invoice_id
where invoice.seminar_id = 6

现在我认为它可以翻译:

from att in context.Attendees
join webUsers in context.WebUsers on webUsers.ID equals att.WebUserID
join invoice in context.Invoice on att.InvoiceID equals invoice.ID
where invoice.SeminarID == seminarId
select new {
  webUsers.FirstName,
  att.InvoiceID                                                       
};