2013-05-27 61 views
1

我在2012年與LINQ中的DateTime的Year整數比較,以及年= 2013的LINQ返回行。我想知道我做了什麼錯誤。在LINQ中比較日期時間的年份返回不正確的結果

var accountBalance_query = from report in context.AccountBalances 
          where report.FiscalYear.Year == reportYear && 
          report.CompanyCode == companyCode && 
          report.AccountNo == accountNo && 
          (subLedgerTypeCode == null) ? report.SubLedgerTypeCode == null : report.SubLedgerTypeCode == subLedgerTypeCode && 
          (subLedgerName == null) ? report.SubLedgerName == null : report.SubLedgerName == subLedgerName && 
          report.AccountCurrencyCode == transactionCurCode 
          select report; 

var reportCnt = accountBalance_query.Count(); 
if (reportCnt > 1) 
{ 
    reason = "Find more than 1 account balance in database that match the following key. " + 
     " CompanyCode = " + companyCode + 
     " AccountNo = " + accountNo + 
     " SubLedgerTypeCode = " + subLedgerTypeCode + 
     " SubLedgerName " + subLedgerName + 
     " Year " + reportYear + 
     " CurrenyCode " + transactionCurCode; 
    return false; 
} 

Model.GeneralLedger.AccountBalance accountBalance; 
if (reportCnt == 1) 
{ 
    accountBalance = accountBalance_query.First(); 
} 

enter image description here

+2

請更多關注在未來的格式 - 這是無助於必須水平在所有的滾動,更別說當每一行的第一個12個或16個字符都是空格。 –

+2

數據庫中的'FiscalYear'類型是什麼?我想知道這是否是一個時區問題...... –

+0

2013-01-01 00:00:00.000 in DB –

回答

0

找到原因。需要兩個以上括號內爲空校驗條件

 var accountBalance_query = context.AccountBalances.Where(report => report.FiscalYear.Year == 2012 && 
        report.CompanyCode == companyCode && 
        report.AccountNo == accountNo && 
        ((subLedgerTypeCode == null) ? report.SubLedgerTypeCode == null : report.SubLedgerTypeCode == subLedgerTypeCode) && 
        ((subLedgerName == null) ? report.SubLedgerName == null : report.SubLedgerName == subLedgerName) && 
        report.AccountCurrencyCode == transactionCurCode); 
1

與lambda表達式試一試,看看會發生什麼。我在一週前有過類似的查詢,它使用的是lambda表達式。

context.AccountBalances.Where(report => report.FiscalYear.Year == reportYear && 
         report.CompanyCode == companyCode && 
         report.AccountNo == accountNo && 
         (subLedgerTypeCode == null) ? report.SubLedgerTypeCode == null : report.SubLedgerTypeCode == subLedgerTypeCode && 
         (subLedgerName == null) ? report.SubLedgerName == null : report.SubLedgerName == subLedgerName && 
         report.AccountCurrencyCode == transactionCurCode); 
+0

感謝您的回覆。結果是一樣的。 –

+0

當你在where子句中放置report.FiscalYear.Year == reportYear時, –

相關問題