2010-04-21 49 views
2

我有一个不是返回适当的响应LINQ表达式正确

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

问题如下LINQ表达式在于Estimator = (quote.EstimatorID != null && quote.EstimatorID != String.Empty) ? db.Employees.Single(c => c.EmployeeID == quote.EstimatorID).FullName : "Unassigned"部分。

我从来没有得到它评价为“未分配”,在那些应该是,它只是返回null。我写错了吗?

+0

有一个函数:'string.IsNullOrEmpty' http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx – 2010-04-21 22:58:42

+1

是否quote.Estimator评估为null或String .Empty'? – 2010-04-21 23:02:49

+0

是的,偶尔会。这是我继承的旧数据库。 – WedTM 2010-04-21 23:04:02

回答

1

试试这个,看看您是否收到相同的价值观:

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

如果还是不行,请尝试更换检查三元表达与假,看看(string.IsNullOrEmpty部分!)如果你达到“未分配”。我发现有时候,当你在LINQ查询中使用三元表达式时,你必须把整个东西包装在括号内。

+0

添加了一个针对修剪的EstimatorID的支票。我有单空间值在ADO.NET中创建了一个调试噩梦。我相信LINQ to SQL和EF会自动修剪,但我不会依赖它。 – 2010-04-21 23:10:02

+0

我尝试添加你的,但是当运行查询时,我收到DataBind上一个极其神秘的错误。 但是当我输入错误时,它运行得很好。 – WedTM 2010-04-21 23:14:28

+0

这很奇怪。我确实有一个太多的左括号,并在你发布的时间里修改了我的答案。这听起来像Single没有回报你所期望的。也许改成'db.Employees.Select(c => c.EmployeeID == quote.EstimatorID).SingleOrDefault()'?这是一个选项吗? – 2010-04-22 00:10:38

1

我认为您的表情是正确的,但我建议将其更改为!string.IsNullOrEmpty(quote.EstimatorID)以清晰起见。

但请注意,如果db.Employees.Single(c => c.EmployeeID == quote.EstimatorID).FullName返回null,则表达式仍然可以返回null。

0

然后它看起来像quote.EstimatorID不是空字符串或空字符串。 db.Employees.Single()在这里返回null吗?调试它 - 将断点放入表达式的这些部分(如果需要,将它们放在不同的行上)。如果你不能这样做,那么围绕它们的方法就是调用Debug.WriteLine()或类似方法。