问题:以下{{1}中Index()
操作方法中使用的扩展方法" Include"的方式和位置在下面显示的PostController
中使用?据我所知Inxex.cshtml view
表示包含与博客表相关的所有帖子。但是我没有在下面的Index.cshtml视图中看到使用博客类_context.Posts.Include(p => p.Blog)
属性?
背景:在ASP.NET MVC核心 - Code First项目中,我跟随this ASP.NET official site tutorial,他们有or blogId
(父级)的以下模型类, Blog
(孩子)。然后我使用Post
向导创建了一个控制器(如下所示),我在模型对话框中选择了MVC Controller with Views, using Entity Framework
模型:
模型:
Post
PostController中:
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace EFGetStarted.AspNetCore.NewDb.Models
{
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
PostController中的Index()操作的Index.cshtml视图:
public class PostsController : Controller
{
private readonly BloggingContext _context;
public PostsController(BloggingContext context)
{
_context = context;
}
// GET: Posts
public async Task<IActionResult> Index()
{
var bloggingContext = _context.Posts.Include(p => p.Blog);
return View(await bloggingContext.ToListAsync());
}
}
答案 0 :(得分:0)
由于您没有访问Blog属性,因此最好不要使用Include(p =&gt; p.Blog)。这将添加一个不需要的额外连接。 但是,如果您将在每个表行中引用它,那么最好包含它以避免延迟加载问题。