简体   繁体   中英

Self Join or Inner Query in a table with Linq to SQL

I have two tables User & Employee .

+-------Supervisor----------+
SupervisorId
Password
+---------------------+


+-------Employee----------+
EmployeeId
EmployeeSupervisorId
EmployeeName
+---------------------+

This is what I am doing so far

SupervisorName = db.Employee.Where(m => m.EmployeeSupervisorId == m.SupervisorId).Select(q => q.EmployeeName).ToList()

I am not understanding the concept of how I join my Employee table to itself so that I can get a list of Employee and their corresponding Supervisor Name

You can do the below

SupervisorName = db.Employee
                   .Join(db.Supervisor, 
                        emp => emp.EmployeeSupervisorId,
                        sup => sup.SupervisorId,
                        (emp, sup)=> new {SupervisorName = emp.EmployeeName})
                   .Select(x=>x) 
                   .ToList();
SupervisorName  = db.Employee.
                  Join(db.Supervisoer, e => e.EmployeeSupervisorId, s => s.SupervisorId, (e, s) => new { Employee = e, Supervisor = s}.
                  ToList().
                  Select(e => e.EmployeeName).
                  ToList();

You can use a simple subquery like this

var result = db.Employee.Select(e => new
{
    Employee = e,
    SupervisorName = db.Employee
        .Where(s => s.EmployeeId == e.EmployeeSupervisorId)
        .Select(s => s.EmployeeName).FirstOrDefault()        
}).ToList();

Note that if you have EmployeeSupervisorId defined as a foreign-key pointing back to EmployeeId, the Linq2Sql will automatically create a EmployeeSupervisor property (which would be an Employee object)

   var list = from e in db.Employee
    //        where e.......  
              select new {
                 Name = e.EmployeeName,
                 Supervisor = e.EmployeeSupervisor.EmployeeName,
    //           otherdetails = e......
                 }

If you haven't defined the foreign key, you have to specify it explicitly in the query:

   var list = from e in db.Employee
              join s in db.Employee on e.EmployeeSupervisorId equal s.EmployeeId
    //        where e.......  
              select new {
                 Name = e.EmployeeName,
                 Supervisor = s.EmployeeName,
    //           otherdetails = e......
                 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM