2014-01-24 42 views
0

我有4個表。我想創建linq查詢使用加入和誰是所有活躍的僱主提取數據。我的表是,使用linq查詢連接多個表並按表排序

1.喬布斯

EmployerId 

2. Employerregistrationddetails

Employerid 

    planid 

    amount 

3 EmployerPlans

planid 

    alerts 

4. AlertDones

employerid 

    alertssent 

在作業表employerid等於* Emp_Reg_Details.employerId *和* emp_reg_details.planId *等於employerplans.planIdEmployerplans.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變量..我做了任何錯誤,請澄清我?

回答

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,在這種情況下,empnull