Bryan Fok
Bryan Fok

Reputation: 3487

Compare Datetime's Year in LINQ return incorrect result

I am comparing 2012 with DateTime's Year integer in LINQ, and the LINQ return row with Year = 2013. I am wondering what wrong have I done.

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

Upvotes: 1

Views: 291

Answers (2)

Bryan Fok
Bryan Fok

Reputation: 3487

Find the reason. Need two more brackets for the null check conditions

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

Upvotes: 0

Johannes Wanzek
Johannes Wanzek

Reputation: 2875

Try it with a lambda expression and see what happens. I had some similar query a week ago and it was working using a lambda expression.

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

Upvotes: 1

Related Questions