简体   繁体   中英

SQL query to LINQ expression

I cannot make the following query into LINQ expression. Could you help me ?

 SELECT Employee_Id_FK from TimeRegistrations as tr
  JOIN Employees em ON tr.Employee_Id_FK = em.id
  JOIN Managers m  ON em.Manager_Id_FK = m.id
  WHERE m.id = 4 

This is what I have so far :

var result = from t in DB.TimeRegistrations
     join Employees  in DB.TimeRegistrations on t.Employee_Id_FK equals Employees.id
     join Managers in DB.Managers on .....          ;

// Display results.
foreach (var r in result)
{
Console.WriteLine(r);
}

In case your db has foreign keys:

 var result =from t1 in DB.TimeRegistrations
     join t2 in t1.Employees 
     join t3 in t2.Managers 
     where t3.id == "4"
     select t1

in case it does not:

 var result =from t1 in DB.TimeRegistrations
     join t2 in DB.Employees on t1.Employee_Id_FK equals t2.id
     join t3 in DB.Managers on t2.id equals t3.Manager_Id_FK 
     where t3.id == "4"
     select t1

However shorter way will be:

 var result = DB.Managers.Find(4).Employees.SelectMany(e=>e.TimeRegistrations)

Or not that straight forward way:

 var result = DB.TimeRegistrations
                .Where(t=>t.Employees.Any(e=>e.Managers.Any(m=>m.id == 4)))

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