2016-09-10 21 views
0

に質問インクルードの使用:どのようにして拡張メソッド「Include」、下に示すInxex.cshtml viewで使用される以下のPostControllerで、Index()アクションメソッドで使用されるの?私が理解しているように、_context.Posts.Include(p => p.Blog)には、ブログテーブルに関連するすべての投稿が含まれています。しかし、私は下のIndex.cshtmlビューでブログクラスor blogIdプロパティの使用を見ていないのですか?Entity Frameworkのコア

背景:ASP.NET MVCのコアで - 彼らはBlog(親)とPostのモデルクラス(子)を以下のいるところ私はthis ASP.NET official site tutorialを以下のよコードまずプロジェクト。 Iは、モデルダイアログボックスのPostモデルを選択した場合、私は、その後MVC Controller with Views, using Entity Frameworkウィザードを使用して、(以下に示す)コントローラを作成した:

モデル

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

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

をPostControllerのIndex()アクションのIndex.cshtmlビュー

@model IEnumerable<ASP_Core_Blogs.Models.Post> 

@{ 
    ViewData["Title"] = "Index"; 
} 

<h2>Index</h2> 

<p> 
    <a asp-action="Create">Create New</a> 
</p> 
<table class="table"> 
    <thead> 
     <tr> 
      <th> 
       @Html.DisplayNameFor(model => model.Content) 
      </th> 
      <th> 
       @Html.DisplayNameFor(model => model.Title) 
      </th> 
      <th></th> 
     </tr> 
    </thead> 
    <tbody> 
@foreach (var item in Model) { 
     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.Content) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.Title) 
      </td> 
      <td> 
       <a asp-action="Edit" asp-route-id="@item.PostId">Edit</a> | 
       <a asp-action="Details" asp-route-id="@item.PostId">Details</a> | 
       <a asp-action="Delete" asp-route-id="@item.PostId">Delete</a> 
      </td> 
     </tr> 
} 
    </tbody> 
</table> 

答えて

0

ブログのプロパティにアクセスしていないので、インクルード(p => p.Blog)を使用しない方が良いです。これにより、不要な追加の結合が追加されます。 ただし、各テーブル行で参照する場合は、遅延読み込みの問題を避けるために含めることをお勧めします。

関連する問題