2017-10-12 71 views
3

只是試圖讓我的@item.BlogCategories.CategoryName顯示類別, 但它說沒有設置對象。我檢查了數據庫。和BlogCategoryId是正確的。如果這是MVC5,它不會是一個問題。 MVC內核有什麼不同?.NET Core 2.0 - 來自BlogItem的BlogCategory

它寫入@items正確,@item.Title,ID的其餘部分等


的NullReferenceException:對象沒有設置爲一個對象的一個​​實例。

<a href="#">@item.BlogCategories.CategoryName</a> 

public class BlogItem 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    [MaxLength(100)] 
    [Required] 
    public string BodyText { get; set; } 
    public string Image { get; set; } 
    public DateTime DateCreated { get; set; } 
    public int Views { get; set; } 
    public string UserId { get; set; } 
    public virtual ApplicationUser User { get; set; } 

    public virtual IEnumerable<ImageTag> Tags { get; set; } 

    public int BlogCategoryId { get; set; } 
    public virtual BlogCategory BlogCategories { get; set; } 
} 

private readonly BlogDbContext db; 

    public HomeController(BlogDbContext context) 
    { 
     db = context; 
    } 
    #endregion 
    public IActionResult Index() 
    { 
     List<BlogItem> bi = db.BlogItems.OrderByDescending(m => m.DateCreated).ToList(); 
     return View(bi); 
    } 

回答

5

實體框架的核心沒有做懶加載(至少,not yet),所以你需要明確你所需要的子屬性。例如:

List<BlogItem> bi = db.BlogItems 
    .Include(bi => bi.BlogCategory) 
    .OrderByDescending(m => m.DateCreated) 
    .ToList();