gpt4 book ai didi

c# - .NET Core 2.0 - 来自 BlogItem 的 BlogCategory

转载 作者:行者123 更新时间:2023-11-30 14:47:07 25 4
gpt4 key购买 nike

只是想让我的 @item.BlogCategories.CategoryName 显示类别,但它说对象未设置。我检查了数据库。 BlogCategoryId 是正确的。如果这是 MVC5,那将不是问题。 MVC 核心有什么不同?

它写入其余的 @items 正确,@item.Title,id 等。


NullReferenceException: Object reference not set to an instance of an object.

<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);
}

最佳答案

Entity Framework Core 不执行延迟加载(至少 not yet ),因此您需要明确说明所需的子属性。例如:

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

关于c# - .NET Core 2.0 - 来自 BlogItem 的 BlogCategory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46713512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com