How to join linq query in ASP.NET MVC

Hi Everyone,
I am working with MVC, C#  I have two model classes, Trainer and Course. I want a method to return information of both models, I created already the database with two tables Trainer and Course joined by TrainerID. I want to join both table to assign Course to trainer. How I can do this?

Model Classes:

 public class Trainer
 {
        public int TrainerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public virtual List<Course> Courses { get; set; }
 }

public class Course
{
        public int CourseID { get; set; }
        public string CourseName { get; set; }
        public virtual Trainer Trainer{ get; set; }
        public int TrainerID{ get; set; }              
}

Controller:

public class opp
{
        MyDbContext db = new MyDbContext();
        public List<Course> CourseTaughtByTrainer()
        {
            var temp = (from ar in db.Trainer
                        join al in db.Course on ar.TrainerID  equals al.TrainerID 
                        select new { al.CourseName , ar.FirstName, ar.LastName });
                        return temp;
        }
}
Can anyone give me a solution.
Thank you.
Last updated:3/28/2016 11:49:40 PM

1 Answers

Anupam Mishra
Anupam Mishra

Hi Manoj,

You need to create a viewModel to get and set their value:

 public class CourseTaughtByTrainer
 {
       public string CourseName {get;set;}
       public string FirstName {get;set}
       public string LastName {get;set;}
 }
and return that like:

public List<CourseTaughtByTrainer> CourseByTrainer()
{
    var temp = (from ar in db.Trainer
                join al in db.Course on ar.TrainerID equals al.TrainerID 
                select new CourseTaughtByTrainer
                { 
                   CourseName =al.CourseName, 
                   FirstName = ar.FirstName, 
                    LastName  = ar.LastName 
                });
    return temp;
}

Answer