当数据库表中没有记录时获取Null引用异常。 [英] Getting Null Reference Exception when there are no records in database table.
本文介绍了当数据库表中没有记录时获取Null引用异常。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在视图中获得以下代码的空引用异常。
I am getting null reference exception for the following code in the view.
@if (Model.OperatorNotes.ApprovedBy.HasValue) // null reference exception
{
<div class="row form-group">
<div class="col-xs-2 col-md-2 col-s-2">
Approved By
</div>
<div class="col-xs-10 col-md-10 col-s-10">
@UserHelper.GetUsername(Model.OperatorNotes.ApprovedBy.Value)
</div>
</div>
}
当表'OperatorNotes'中有记录时,没有异常被提出。
我该如何解决这个问题?我应该使用什么而不是'@if(Model.OperatorNotes.ApprovedBy.HasValue)'
when there are records in the table 'OperatorNotes' no exception is raised.
How should i resolve this? what should i be using instead of '@if (Model.OperatorNotes.ApprovedBy.HasValue)'
推荐答案
尝试测试 OperatorNotes $在尝试访问其中一个属性之前,c $ c> null
的属性:
Try testing theOperatorNotes
property fornull
before trying to access one of its properties:
@if (Model.OperatorNotes != null && Model.OperatorNotes.ApprovedBy.HasValue)
或者,如果你'使用C#6,您可以使用 Null条件运算符 [ ^ ]:
Alternatively, if you're using C# 6, you could use the Null-conditional operator[^]:
@if (Model.OperatorNotes?.ApprovedBy.HasValue)
(注意额外的?
in属性访问: OperatorNotes ?。 ApprovedBy
)
(Note the extra ?
in the property access: OperatorNotes?.ApprovedBy
)
这篇关于当数据库表中没有记录时获取Null引用异常。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文