2017-10-12 100 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();