带有if语句的LINQ查询结构

本文关键字:查询 结构 LINQ if 语句 带有 | 更新日期: 2023-09-27 18:22:51

我构建了一个完整的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 =语句的情况下,我上面试图做的事情可能吗?

带有if语句的LINQ查询结构

为什么不创建一个查询,然后如果不是团队负责人,在将查询发送到数据源之前添加额外的join/where子句

即:

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
            });