2013-07-17 259 views
0

我有一個完整的LINQ查詢。如果用戶是經理/團隊領導,並且如果他們不是,則需要運行單獨的查詢,我需要運行一個查詢。但是查詢非常相似。帶有if語句的LINQ查詢結構?

經理/團隊可以看到一切。其他人只能看到他們的認證。

var model = (from d in department 
       join f in db.IPACS_Function on d.departmentID equals f.departmentID 
       join pg in db.IPACS_Process on f.functionID equals pg.functionID 
       join sop in db.IPACS_Procedure on pg.processID equals sop.processID 
       // Non-Manager/Teamlead portion 
       join cert in db.IPACS_Certification on sop.procedureID equals cert.procedureID 
       join procdoc in db.IPACS_ProcedureDocs on sop.procedureID equals procdoc.procedureID 
       join doc in db.IPACS_Document on procdoc.documentID equals doc.documentID 
       where cert.adUserName == currUser && cert.certifiedDate > doc.dateApproved 
       // End non-manager/team lead 
       select new IPACS_DT_MasterList 
       { 
        departmentID = d.departmentID, 
        functionID = f.functionID, 
        processID = pg.processID, 
        procedureID = sop.procedureID, 
        departmentName = d.name, 
        functionName = f.name, 
        processName = pg.name, 
        procedureName = sop.name, 
        owner = sop.owner, 
        automated = (bool)sop.automated 
       }); 

是我試圖做的以上可能沒有創建兩個單獨的var model =語句?

+0

什麼是你的LINQ提供程序?在LINQ to Objects中,if語句當然不是問題。我會想象LINQ to SQL會生成適當的case語句,但我不確定是這種情況。 – evanmcdonnal

+0

爲什麼你會編寫代碼,從我所看到的情況來看,它會被刻意降低可讀性和可維護性? –

+0

@AdrianWragg我一般都認同他的數據源需要6個連接,所以它不會像其他格式的可讀性更好。如果您可以更改SQL架構,這將是首選的解決方案,但這很少是一種選擇。 – evanmcdonnal

回答

2

爲什麼不創建一個查詢,然後如果不是teamleader添加額外的加入/在查詢之前的條款被髮送到數據源

即:

var query = (from d in department 
      join f in db.IPACS_Function on d.departmentID equals f.departmentID 
      join pg in db.IPACS_Process on f.functionID equals pg.functionID 
      join sop in db.IPACS_Procedure on pg.processID equals sop.processID 

      select new {d, f, pg, sop}); 



if (!TeamLeader){ 
     query = from x in query 
      // Non-Manager/Teamlead portion 
      join cert in db.IPACS_Certification on x.sop.procedureID equals cert.procedureID 
      join procdoc in db.IPACS_ProcedureDocs on x.sop.procedureID equals procdoc.procedureID 
      join doc in db.IPACS_Document on procdoc.documentID equals doc.documentID 
      where cert.adUserName == currUser && cert.certifiedDate > doc.dateApproved 
      // End non-manager/team lead 
      select x; 
} 

var model = (from x in query 
      select new IPACS_DT_MasterList 
      { 
       departmentID = x.d.departmentID, 
       functionID = x.f.functionID, 
       processID = x.pg.processID, 
       procedureID = x.sop.procedureID, 
       departmentName = x.d.name, 
       functionName = x.f.name, 
       processName = x.pg.name, 
       procedureName = x.sop.name, 
       owner = x.sop.owner, 
       automated = (bool)x.sop.automated 
      }); 
+0

經過測試和工作!非常感謝你。 :) –

+0

不客氣:) –