我有一个WebAPI控制器需要从数据库返回一个集合,但我还需要从某些实体中删除一些属性。但是,出于某种原因,当我在调试模式中单步执行代码时,表示另一个实体的属性将返回null,除了有时。我已经在下面显示了json响应,其中显示Sport,HomeTeam和AwayTeam为null:
但是当我在调试模式中跳过代码时,我得到了预期的结果:
相关的控制器方法如下
public dynamic Get()
{
var allPicks = _db.Picks;
if (User.Identity.IsAuthenticated)
{
string userId = User.Identity.GetUserId();
var picks = _db.UnlockedPicks
.Include(p => p.SelectedPick.AwayTeam)
.Include(p => p.SelectedPick.HomeTeam)
.Include(p => p.SelectedPick.Sport)
.Where(p => p.UserId == userId);
var unlockedPicks = picks.Select(p => p.SelectedPick);
var otherPicks = allPicks.Except(unlockedPicks).Select(p => new
{
Analysis = "",
PickSummary = "",
Title = p.Title,
Id = p.Id,
Sport = p.Sport,
HomeTeam = p.HomeTeam,
AwayTeam = p.AwayTeam,
MatchTime = p.MatchTime,
PublishTime = p.PublishTime
});
return new
{
UnlockedPicks = unlockedPicks.OrderByDescending(p => p.MatchTime),
OtherPicks = otherPicks.OrderByDescending(p => p.MatchTime)
};
}
var publicPicks = allPicks.OrderByDescending(p => p.MatchTime).Select(p => new
{
Analysis = "",
PickSummary = "",
Title = p.Title,
Id = p.Id,
Sport = p.Sport,
HomeTeam = p.HomeTeam,
AwayTeam = p.AwayTeam,
MatchTime = p.MatchTime,
PublishTime = p.PublishTime
});
return new { UnlockedPicks = new Pick[0], OtherPicks = publicPicks };
}
没有Include()
它每次都返回null但是我怎样才能让它每次返回预期的结果?
答案 0 :(得分:0)
这是因为您没有使用延迟加载。延迟加载延迟时,您必须调用function YPE_bstab(&$item_output, $item) {
$YPE_categories = get_terms('category', array(
'orderby' => 'count',
'number' => $item->items_num,
'order' => 'DESC',
'hide_empty' => 1
));
$item_output .= '<ul class="nav nav-tabs">';
foreach ($YPE_categories as $YPE_category) {
$item_output .= '<li>';
$item_output .= '<a href="#'.$YPE_category->slug.'" data-toggle="tab">'.$YPE_category->name.'</a>';
$item_output .= '</li>';
}
$item_output .= '</ul>';
$item_output .= '<div class="tab-content">';
foreach ($YPE_categories as $YPE_category) {
$item_output .= '<div class="tab-pane" id="'.$YPE_category->slug.'">';
$YPE_Query = array('posts_per_page' => $item->items_num,'category_name' => $YPE_category->slug);
$YPE_cat_query = new WP_Query($YPE_Query);
while ($YPE_cat_query->have_posts()) {
$YPE_cat_query->the_post();
$item_output .= '<a href="'.get_permalink().'">'.get_the_post_thumbnail(get_the_ID()).'</a>';
$item_output .= '<p><a href="'.get_permalink().'">'.get_the_title().'</a></p>';
}
wp_reset_query();
$item_output .= '</div>';
}
$item_output .= '</div>';
}
才能加载导航属性。如果要加载所有导航属性而不调用Include
,则必须激活延迟加载,这可以通过上下文的构造函数完成。像这样:
Include
默认情况下应激活延迟加载。您可能已将其停用在代码中的其他位置。每次在调试模式下检查导航属性时,也会自动调用它。