Asp mvc 5 relationship many-to-many

asp.net-mvc entity-framework-6 many-to-many

Question

How to display all of the materials in the table Material on the page, as well as a number of related data from the Teacher table? How do I best remake?

Here I describe the models Models:

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

The connection to the database 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"));
       }
    }

Controller:

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

View:

@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
1
5/18/2016 6:44:06 AM

Popular Answer

this might work:

@foreach (var p in Model.Materials)
{
   <p>@p.MaterialDescription</p>
    foreach (Teacher t in p.Teachers)
    {
        <li>@t.TeacherName</li>
    }
}     
1
5/18/2016 7:11:53 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow