2016-05-18 16 views
1

教材のすべての資料をページ上の教材と教師用テーブルからの関連データの数を表示するにはどうすればいいですか? どのようにしてリメイクするのが最適ですか?ここでAsp mvc 5関係many-to-many

私がモデルに モデルについて説明します

public class Teacher 
    { 
     public int TeacherId { get; set; } 
     public string TeacherName { get; set; } 

     public virtual ICollection<Material> Materials { get; set; } 

     public Teacher() 
     { 
      Materials = new List<Material>(); 
     } 
    } 

public class Material 
    { 


     public int MaterialId { get; set; } 
     public string MaterialName { get; set; } 
     public string MaterialDescription { get; set; } 

     public virtual ICollection<Teacher> Teachers { get; set; } 
     public Material() 
     { 
      Teachers = new List<Teacher>(); 
     } 
    } 

データベースへの接続 EfdbContext

public class EfDbContext : DbContext 
    { 
     // For Science Controller 
     public DbSet<Teacher> Teachers { get; set; } 
     public DbSet<Material> Materials { get; set; } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<Teacher>().HasMany(c => c.Materials) 
       .WithMany(s => s.Teachers) 
       .Map(t => t.MapLeftKey("TeacherId") 
       .MapRightKey("MaterialId") 
       .ToTable("TeacherMaterials")); 
     } 
    } 

コントローラー:

public class ScienceController : Controller 
    { 
     EfDbContext context = new EfDbContext(); 
     // GET: Science 
     public ActionResult ScienceResult() 
     { 

      IQueryable<Material> materials = context.Materials.Include(p => p.Teachers); 
      IQueryable<Teacher> teachers = context.Teachers.Include(p => p.Materials); 
      MateriaLTeacherListView materiaLTeacher = new MateriaLTeacherListView() 
      { 
       Materials = materials.ToList(), 
       Teachers = teachers.ToList()     
      };  
      return View(materiaLTeacher); 
     } 
    } 

ビュー:

@using Diploma.Domain.Entities 

@model Diploma.WebUI.Models.MateriaLTeacherListView 

@{ 
    ViewBag.Title = "ScienceResult"; 
} 

<div> 

    @foreach (var p in Model.Materials) 
    { 
     <p>@p.MaterialDescription</p> 
     foreach (Teacher t in Model.Teachers) 
     { 
      <li>@t.TeacherName</li> 
     } 
    }  
</div> 

答えて

1

これはうまくいくかもしれない:

@foreach (var p in Model.Materials) 
{ 
    <p>@p.MaterialDescription</p> 
    foreach (Teacher t in p.Teachers) 
    { 
     <li>@t.TeacherName</li> 
    } 
}  
+1

はどうもありがとうございました!!!) –

関連する問題