2013-04-25 93 views
0

關於下面的查詢,爲什麼我的條件是ingored?實體框架,爲什麼我的被忽略的地方?

public static List<Sys.Entities.Hms206> Hms206Get(DateTime startDate, DateTime endDate, string courseNumber, bool sOnly) { 
    //select distinct 
    // p.DEPTID [Rc], 
    // p.NAME [EmployeeName], 
    // p.EMPLID [EmployeeId], 
    // x.XLATSHORTNAME [Ran] 
    //from 
    // tablep p 
    // inner join tablex x on p.CM_RAN = x.FIELDVALUE 
    // inner join tablet t on p.EMPLID = t.EMPLID 
    //where 
    // p.DEPTID not like '%R' 
    // and p.EMPL_STATUS in('A','L','P','S','W') 
    // and t.COURSE_END_DT between '7/1/1960' and '12/27/2012' 
    // and t.COURSE = 'C00005' 
    // and t.ATTENDANCE = 'C' 
    // and x.FIELDNAME = 'CM_RAN' 

    // and p.CM_IND = 'S' 
    // --and p.CM_IND in ('S','C') -- all 
    //order by 
    // p.DEPTID, p.NAME 
    string[] stats = new string[]{"A","L","P","S","W"}; 
    using (var context = new Sys.EntityModels.LCEntities()) { 
     var query = (from p in context.PsCmSummaries 
         join x in context.TableX on p.CM_RAN equals x.FIELDVALUE 
         join t in context.TableT on p.EMPLID equals t.EMPLID 
         where !p.DEPTID.EndsWith("R") 
         && stats.Contains(p.EMPL_STATUS) 
         && t.COURSE_END_DT >= startDate && t.COURSE_END_DT <= endDate 
         && t.COURSE == courseNumber 
         && t.ATTENDANCE == "C" 
         && x.FIELDNAME == "CM_Ran" 
         select new { 
          p.DEPTID, 
          p.NAME, 
          p.EMPLID, 
          x.XLATSHORTNAME, 
          p.CM_IND 
         }); 
     // this conditional where is not being applied 
     if (sOnly) { 
      query.Where(x => x.CM_IND == "S"); 
     } 
     else { 
      query.Where(x => x.CM_IND == "S" || x.CM_IND == "C"); 
     } 

     return query.Distinct().OrderBy(x => x.DEPTID).ThenBy(x => x.NAME) 
      .Select( 
       x => new Sys.Entities.Hms206 { 
        Rc = x.DEPTID, EmployeeName = x.NAME, EmployeeId = x.EMPLID, 
      Rank = x.XLATSHORTNAME, S_Indicator = x.CM_IND 
      }) 
      .ToList(); 
    } 
} 

回答

1

你打電話Where但完全無視返回值 - 這使得調用無用(注註釋掉sql語句是什麼,我試圖在這個LINQ查詢複製)。你想要的東西,如:

if (sOnly) { 
    query = query.Where(x => x.CM_IND == "S"); 
} 
else { 
    query = query.Where(x => x.CM_IND == "S" || x.CM_IND == "C"); 
} 

LINQ調用,如WhereSelect等不修改現有查詢 - 它們通過合成新方面前面的查詢返回查詢。

+0

笑,我笨!謝謝! – 2013-04-25 06:00:44

2

你可以試試這個來代替你的conditon:

if (sOnly) { 
    query.Where(x => x.CM_IND == "S"); 
} 
else { 
    query.Where(x => x.CM_IND == "S" || x.CM_IND == "C"); 
} 

有了答案下面

query = sOnly ? query.Where(x => x.CM_IND == "S") 
       : query.Where(x => x.CM_IND == "S" || x.CM_IND == "C"); 
+0

謝謝你對使用三元運算符的建議。 – 2013-04-25 06:00:26

+0

沒問題,我剛剛用@Jon Skeet的回答來提示它 – lexeRoy 2013-04-25 06:17:49