这个问题通常发生在使用Entity Framework Core的时候。 解决办法是使用Include来加载相关数据,而非ThenInclude。 举个例子,假设我们有两个模型,一个是Blog,另一个是BlogPost,两个模型之间是一对多的关系。 Blog模型:
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection BlogPosts {get; set; }
}
BlogPost模型:
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
在控制器中,我们需要使用Include来加载BlogPosts集合:
public IActionResult Index()
{
var blogs = _context.Blogs.Include(b => b.BlogPosts);
return View(blogs);
}
在视图中,我们可以访问Blog和BlogPosts的数据:
@foreach (var blog in Model)
{
@blog.Name
@foreach (var post in blog.BlogPosts)
{
- @post.Title
}
}