2015-08-13 29 views
0

如果變量爲null,則無法計算出獲取所有記錄的邏輯否則獲取where officername = officer。獲取所有變量爲空否則匹配

 var res = (from h in db.BalanceHistories 
         where temp.Contains(h.LoanType ?? 0) 
         && ((officer != null && h.OfficerName.ToLower() == officer.ToLower()) || ("Get all records")) 
         group h by new { h.Date.Value.Month, h.Date.Value.Year } into p 
         select new 
         { 
          Month = p.Key.Month, 
          Year = p.Key.Year, 
          Count = p.Count(), 
          Balance = p.Sum(x => x.Balance), 
          Delinquent = p.Sum(x => x.Delinquent) 
         }).ToList(); 

回答

0

只是交換("Get all records")(officer == null),雖然我會建議你把這個情況在第一。

說明:

如果officer == null比對於短circut法律我們將返回true和我們條件的其餘部分將沒有關係。

否則表示officer != null,因此我們想檢查它是否與我們的h.OfficerName數據匹配。

最終結果:

res = (from h in db.BalanceHistories 
        where temp.Contains(h.LoanType ?? 0) 
        && (
         officer == null 
         || h.OfficerName.ToLower() == officer.ToLower()) 
        ) 
        group h by new { h.Date.Value.Month, h.Date.Value.Year } into p 
        select new 
        { 
         Month = p.Key.Month, 
         Year = p.Key.Year, 
         Count = p.Count(), 
         Balance = p.Sum(x => x.Balance), 
         Delinquent = p.Sum(x => x.Delinquent) 
        }).ToList(); 
1

雖然您可以製作複合if語句,但它會(通常 - 現在始終)將此複合語句傳遞到數據庫。在許多情況下,這可能會導致索引缺失,如果正確完成不會錯過。在非Microsoft SQL服務器中,這些類型的查詢也只是簡單地不起作用(MySQL,DB2)。這是更好地只寫正確的查詢擺在首位:

var query = db.BalanceHistories 
    .Where(h=>temp.Contains(h.LoanType ?? 0)); 
if (officer!=null) 
{ 
    // Depending on your database, the ToLower()s here may not be needed. 
    query=query.Where(h=>h.OfficerName.ToLower() == officer.ToLower())) 
} 
var res=(from h in query 
     group h by new { h.Date.Value.Month, h.Date.Value.Year } into p 
     select new 
         { 
          Month = p.Key.Month, 
          Year = p.Key.Year, 
          Count = p.Count(), 
          Balance = p.Sum(x => x.Balance), 
          Delinquent = p.Sum(x => x.Delinquent) 
         }); 
0

你試過:

var res = (from h in db.BalanceHistories 
        where temp.Contains(h.LoanType ?? 0) 
        && ((officer == null) || (h.OfficerName.ToLower() == officer.ToLower())) 
        group h by new { h.Date.Value.Month, h.Date.Value.Year } into p 
        select new 
        { 
         Month = p.Key.Month, 
         Year = p.Key.Year, 
         Count = p.Count(), 
         Balance = p.Sum(x => x.Balance), 
         Delinquent = p.Sum(x => x.Delinquent) 
        }).ToList();