Asp mvc 5关系多对多

时间:2016-05-18 06:44:07

标签: asp.net-mvc entity-framework-6 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 个答案:

答案 0 :(得分:1)

这可能有效:

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