使用linq查询连接多个表并按表排序

时间:2014-01-24 07:09:26

标签: join linq-to-entities

我有4张桌子。我想创建linq查询以使用 join 并获取所有活跃雇主的数据。我的表是,

1。作业

 EmployerId

2。 Employerregistrationddetails

  Employerid

  planid

  amount

第3。 EmployerPlans

  planid

  alerts

4。 AlertDones

  employerid

  alertssent

在Jobs表中,employeeid等于* Emp_Reg_Details.employerId *和* emp_reg_details.planId *等于 employerplans.planId Employerplans.alerts 等于 alertdones。 alertssent 意味着它将首先订购上述条件,然后其余的工作将订购..

我把linq查询为此..但它不完全正常..我的查询是

 return (from job in _db.Jobs 
         join employerregdetails in _db.EmployerRegistrationDetails 
             on job.OrganizationId equals employerregdetails.EmployerId into e
         join ep in _db.EmployerPlans 
             on emp.PlanId equals ep.EmployerPlanId
         join alr in _db.AlertsDones 
             on ep.Alerts equals alr.AlertsSent
         from emp in e.DefaultIfEmpty()

         orderby job.OrganizationId != -1 descending, 
                 job.OrganizationId != null descending
         orderby job.OrganizationId != -1 descending, 
                 alr.EmployerId == job.OrganizationId descending, 
                 job.CreatedDate descending
         select job);

如果我使用上述查询,则出现错误emp.PlanId。它没有采取emp变量..我做了任何错误请澄清我?

1 个答案:

答案 0 :(得分:2)

你看不到emp变量,因为它已在你想要引用的行之后定义,你需要在这一行之前定义emp:

join ep in _db.EmployerPlans on emp.PlanId equals ep.EmployerPlanId
像这样:

return (from job in _db.Jobs 
        join employerregdetails in _db.EmployerRegistrationDetails 
            on job.OrganizationId equals employerregdetails.EmployerId into e
        from emp in e.DefaultIfEmpty()
        join ep in _db.EmployerPlans on emp.PlanId equals ep.EmployerPlanId

但请注意,如果jobs没有EmployerRegistrationDetails,您可能会收到错误,因为您尝试使用left join,在这种情况下emp是{{} 1}}