问题描述
我的MVC视图具有以下代码-
My MVC view has the following code -
@foreach (var d in Model.ItineraryDays)
{
<tr>
<td>
@Html.DisplayFor(model => d.DayPlus1)
</td>
<td>
@Html.ActionLink(d.Listing.Name, "Details", "Port", new { Id = d.ListingId }, null)
</td>
<td>
@if (d.Listing.Port.Country != null)
{
@Html.ActionLink(d.Listing.Port.Country.Name, "Details", "Country", new { Id = d.Listing.Port.Country.Id }, null)
}
</td>
当(d.Listing.Port.Country!= null)遇到空值时,它将返回未设置为对象实例的对象引用".
When (d.Listing.Port.Country != null) encounters a null value it returns an 'Object reference not set to an instance of an object.' exception.
Port和Country都是延迟加载属性.如果'Country'!=仔细考虑,则'Port'必须有一个条目.(并非所有列表都在端口中都有一个条目,因此为空检查).
Both Port and Country are lazy loading properties. If 'Country' != mull, then 'Port' must have an entry. (Not all Listings have an entry in Port, hence the null check).
我的方法出了点问题,不确定是什么!
Something wrong with my approach, not sure what!
问候,盖伊
附录:存储库代码:
public Itinerary GetItineraryFromId(int Id)
{
var itinerary = context.Itineraries
.Include(i => i.ItineraryDays)
.Include(i => i.ItineraryStartDates)
.Where(i => i.Id == Id).FirstOrDefault();
return(itinerary);
}
- ItineraryDay具有导航.属性>>公共虚拟列表列表{设置;}
- 列表具有导航.属性>>公共虚拟端口Port {get;放;}
- 端口具有导航.属性>>公共虚拟国家(地区)国家{放;}
推荐答案
由于港口和国家/地区都是延迟加载的,因此您需要在港口级别开始有条件检查
Since both Port and Country are lazy loaded you would need to start your conditional check at the Port level
@if (d.Listing.Port != null) {
if (d.Listing.Port.Country != null) {
... Do Something
}
} else {
... Handle null scenario
}
这篇关于如何检查延迟加载属性是否返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!