2012-02-08 86 views
3

与LINQ查询工作我收到错误LINQ的,如何检查是否字段的值为null

System.NullReferenceException同时:未设置为对象的实例 对象引用。

var db = from d in DepartmentBLL.GetDepartmentList() 
    join b in BudgetMasterBLL.GetBudgetMasterList()    
    on d.Departmentid equals b.Departmentid into leftJoin      
    from results in leftJoin.DefaultIfEmpty() 
    select new 
    { 
     Name = d.Name, 
     Create = results.Budgetmasterid == null ? "null": "value", //ERROR HERE 
     CreateURL = "frmBudgetInitial.aspx?departmentid=" + d.Departmentid.ToString() + "&departmentcategoryid=" + d.Departmentcategoryid.ToString() 
    }; 

我发现论坛上一些帮助,但并没有解决我的问题,请指教。谢谢,

+0

首次检查结果使用results.Budgetmasterid – DotNetUser 2012-02-08 13:30:50

+0

由于results.Budgetmasterid是之前为null字符串值,你不应该检查String.Empty而不是null? – 2012-02-08 13:37:15

回答

3

尝试

Create = results == null || string.IsNullOrEmpty(results.Budgetmasterid) ? "null": "value", 

Create = results == null || string.IsNullOrWhitespace(results.Budgetmasterid) ? "null": "value", 
+0

这似乎是正确的,但与此同时,这不能解决第一个例外。 – 2012-02-08 13:45:11

+0

同意。点(。)仍然可以引用空对象。 – 2012-02-08 13:49:33

+0

@Ales我在你的评论[编辑]弗拉季斯拉夫后编辑。现在呢? – Bastardo 2012-02-08 14:07:45

2

这应该有助于

Create = results == null || results.Budgetmasterid == null ? "null": "value", //ERROR HERE 
+0

如果没有结果返回,这不会将'true'赋值给'Create'吗? – 2012-02-08 13:37:15

+0

没有结果返回时,原始条件成立。我只是保持这一点。 – 2012-02-08 13:41:41

+0

顺便说一句,“结果”甚至可能为空?我的意思是,空集合!= null? – 2012-02-08 13:45:22