如何处理具有外键关系的 asp.net 转发器项中的空引用
How to handle null reference in asp.net Repeater item with foreign-key relations
我在 asp.net 转发器控件中遇到空引用问题。
转发器遍历具有引用属性的 class 的 IEnumerable<T>
。
我有以下 classes:
public class SubTarget
{
public int Id { get; set; }
public string Name { get; set; }
public int? ModelId { get; set; }
public virtual Model Model { get; set; }
}
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public Model()
{
SubTargetTypes = new HashSet<SubTargetType>();
}
}
和中继控制:
<asp:Repeater
runat="server" ItemType="SubTarget" SelectMethod="GetSubTargets">
<ItemTemplate>
<div>
<table>
<tr>
<td><%# Item.SubTargetType.Name %></td>
<td><%# Item.Model.Name %></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
问题是:Model
属性 on SubTarget
是可选的。所以当 ModelId
为 null 时,显然找不到对 Model
上的属性的引用。
转发器控件在仅使用 <%# Item.Model %>
调用时正确处理空值 ModelId
并将 space 留空,但在调用 <%# Item.Model.Name %>
时我得到空引用异常。
知道如何在未设置外键时只显示空白 space 吗?
试试这个:
<td><%# Item.Model !=null ? Item.Model.Name : string.Empty %></td>
希望对你有帮助。 :)
我在 asp.net 转发器控件中遇到空引用问题。
转发器遍历具有引用属性的 class 的 IEnumerable<T>
。
我有以下 classes:
public class SubTarget
{
public int Id { get; set; }
public string Name { get; set; }
public int? ModelId { get; set; }
public virtual Model Model { get; set; }
}
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public Model()
{
SubTargetTypes = new HashSet<SubTargetType>();
}
}
和中继控制:
<asp:Repeater
runat="server" ItemType="SubTarget" SelectMethod="GetSubTargets">
<ItemTemplate>
<div>
<table>
<tr>
<td><%# Item.SubTargetType.Name %></td>
<td><%# Item.Model.Name %></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
问题是:Model
属性 on SubTarget
是可选的。所以当 ModelId
为 null 时,显然找不到对 Model
上的属性的引用。
转发器控件在仅使用 <%# Item.Model %>
调用时正确处理空值 ModelId
并将 space 留空,但在调用 <%# Item.Model.Name %>
时我得到空引用异常。
知道如何在未设置外键时只显示空白 space 吗?
试试这个:
<td><%# Item.Model !=null ? Item.Model.Name : string.Empty %></td>
希望对你有帮助。 :)