开发者

LINQ Expression not evaluating correctly

I have the following LINQ expression that's not returning the appropriate response

    var query = from quote in db.Quotes
                where quote.QuoteStatus == "Estimating" || quote.QuoteStatus == "Rejected"
                from emp in db.Employees
                where emp.EmployeeID == quote.EmployeeID
                orderby quote.QuoteID descending
                select new 
                { 
                    quote.QuoteID, 
                    quote.DateDue, 
                    Company = quote.Company.CompanyName, 
                    Attachments = quote.Attachments.Count, 
                    Employee = emp.FullName, 
                    Estimator =  (quote.EstimatorID != null && quote.EstimatorID != String.Empty) 
                    ? db.Employees.Single (c => c.EmployeeID == quote.EstimatorID).FullName 
                    : "Unassigned", 
                    Status = quote.QuoteStatus, Priority = quote.Priority 
                };

The problem lies in the Estimator = (quote.EstimatorID开发者_如何学编程 != null && quote.EstimatorID != String.Empty) ? db.Employees.Single(c => c.EmployeeID == quote.EstimatorID).FullName : "Unassigned" part.

I NEVER get it to evalueate to "Unassigned", on the ones that are supposed to, it just returns null. Have I written this wrong?


Try this and see if you're receiving the same values:

Estimator = ((!string.IsNullOrEmpty(quote.EstimatorID) && !string.IsNullOrEmpty(quote.EstimatorID.Trim())
? (db.Employees.Single(c => c.EmployeeID == quote.EstimatorID)).FullName 
: "Unassigned")

If that doesn't work, try replacing the check in the ternary expression (!string.IsNullOrEmpty part) with false and see if you reach "Unassigned". I've found that sometimes, when you use a ternary expression in a LINQ query, you have to wrap the whole thing in parentheses.


I think your expression is correct, although I would advise changing it to !string.IsNullOrEmpty(quote.EstimatorID) for clarity.

Note however that your expression could still return null if db.Employees.Single(c => c.EmployeeID == quote.EstimatorID).FullName returns null.


Then it looks like quote.EstimatorID is not null or empty string. Is db.Employees.Single() returning null here? Debug it - put breakpoints into those parts of the expression (putting them on separate lines, if necessary). If you can't do that wrap methods around them that call Debug.WriteLine() or similar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜