C# LINQ to Dataset DBNULL 问题/空引用异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/881225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ to Dataset DBNULL problem / null reference exception
提问by Marc
I have the following LINQ query which always results in an error when my "Remark" column in dtblDetail is null, even though I test if it is NULL.
我有以下 LINQ 查询,当 dtblDetail 中的“备注”列为空时,即使我测试它是否为空,它也总是会导致错误。
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d.IsRemarkNull() ? null : d.Remark
};
The error message was: "The value for column 'Remark' in table 'dtblDetails' is DBNull." After adding the test for d.IsRemarkNull() a null reference exception is thrown.
错误消息是:“表 'dtblDetails' 中列 'Remark' 的值为 DBNull。” 添加 d.IsRemarkNull() 测试后,会抛出空引用异常。
Can you help me with this?
你能帮我解决这个问题吗?
I've already checked the following websites but didn't find anything useful other than that I have to test for DBNULL. But as said this doesn't solve my problem.
我已经检查了以下网站,但除了我必须测试 DBNULL 之外,没有发现任何有用的东西。但正如所说这并不能解决我的问题。
采纳答案by Marc
The problem was that the whole 'd' item was empty. So calling 'd.IsRemarkNull()' resulted in the null reference exception. The following code fixed the problem:
问题是整个“d”项目是空的。因此调用 'd.IsRemarkNull()' 导致空引用异常。下面的代码解决了这个问题:
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d == null? null : (d.IsRemarkNull() ? null : d.Remark)
};
回答by dmo
Where is the error coming from? Is it possible that it is the d.IsRemarkNull() that is causing it? What does that method look like?
错误来自哪里?是否有可能是 d.IsRemarkNull() 导致的?这种方法看起来像什么?
Perhaps:
也许:
DBNull.Value.Equals(d.Remark)
回答by Ada
maybe this field doesn't allow null in db, get a default value for it, and avoid handling null values
也许这个字段不允许在 db 中为 null,为它获取一个默认值,并避免处理 null 值