如何使用select语句中的查询将此SQL语句转换为LINQ to SQL

时间:2011-10-07 15:38:34

标签: sql linq-to-sql

该表格包含staffidfirstnamelastnameemailsupervisoridsupervisorid与同一张桌子上的staffid相关联。

select 
 StaffID,
 FirstName + ' ' + LastName as 'Name',
 Email,
 Supervisor = (Select FirstName + ' ' + LastName
                  From tblStaff staffinner 
            Where staffinner.StaffID = staffouter.SupervisorID)
from tblStaff staffouter

3 个答案:

答案 0 :(得分:1)

var staff = from s1 in tblStaff
            select new
            {
               StaffID = s1.StaffID,
               Name = s1.FirstName + " " + s1.LastName,
               Email = s1.Email,
               Supervisor = (from s2 in tblStaff
                            where s2.StaffID == s1.SupervisorID
                            select s2.FirstName + " " + s2.LastName).First()
            };

答案 1 :(得分:0)

var staff = tblStaff
            .Select(a => new
                         {
                          StaffID = a.StaffID,
                          Name = a.FirstName + " " + a.LastName,
                          Email = a.Email,
                          Supervisor = tblStaff
                                       .Where(b => b.StaffID = a.SupervisorID)
                                       .Select(b => b.FirstName + " " + b.LastName)
                                       .First()
                         };

答案 2 :(得分:0)

你真的需要一个次级选择,还是自我加入就足够了?

var staff = from person in tblStaff
            join supervisor in tblStaff on person.StaffID equals supervisor.SupervisorID
            select new 
            {
                person.StaffID,
                Name = person.FirstName + ' ' + person.LastName,
                person.Email,
                Supervisor = supervisor.FirstName + ' ' + supervisor.LastName
            };

如果需要进行外连接,请使用DefaultIfEmpty()。