Asp mvc 5 relationship many-to-many

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

Question

How can I show every item in the Material table on the page, along with some associated information from the Teacher table? How can I remake the best?

Here is a description of the 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 relationship with 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

ZZZ_tmp
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