locked
Linq query Many to many RRS feed

  • Question

  • User-2132497554 posted

    Hi developer,

    I am using asp.net 5 with EF 7

    Here is my sample code:
    Student.cs

    public class Student
    {
        public Student() { }
    
        public int StudentId { get; set; }
        public string StudentName { get; set; }
    
        public virtual ICollection<StudentCourse> StudentsCourses { get; set; }
    }
            

    Course.cs

    public class Course
    {
        public int CourseId { get; set; }
        public string CourseName { get; set; }
    
        public virtual ICollection<StudentCourse> StudentsCourses { get; set; }
    }
    

    StudentCourse.cs

    public class StudentCourse
    {
    	public int StudentId { get; set; }
    	public class Student { get; set; }
    	
    	public int CourseId { get; set; }
    	public class Course { get; set; }
    }

    MyContext.cs

    class MyContext : DbContext
        {
            public DbSet<Student> Students { get; set; }
            public DbSet<Course> Courses { get; set; }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<StudentCourse>()
                    .HasKey(t => new { t.StudentId, t.CourseId });
    
                modelBuilder.Entity<StudentCourse>()
                    .HasOne(pt => pt.Student)
                    .WithMany(p => p.StudentsCourses)
                    .HasForeignKey(pt => pt.StudentId);
    
                modelBuilder.Entity<StudentCourse>()
                    .HasOne(pt => pt.Course)
                    .WithMany(t => t.StudentsCourses)
                    .HasForeignKey(pt => pt.CourseId);
            }
        }

    StudentController.cs

    // GET: api/Section
    [HttpGet]
    public IEnumerable<Student> GetStudents()
    {
         return _context.Students;
    }
    
    // GET: api/Section/5
    [HttpGet("{id}", Name = "GetStudent")]
    public IActionResult GetSection([FromRoute] int id)
    {
    ........
        Student student = _context.Students.Single(m => m.StudentId == id);
    ...............
    ..............
    }

    How to write linq query for junction table (Student and Course) if many to many relationship?
    I am waiting for your response.

    Thanks

    Tuesday, January 26, 2016 7:34 AM

Answers

All replies