Home > DeveloperSection > Forums > How to join linq query in ASP.NET MVC
Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    March-28-2016 11:38 PM

 ASP.NET MVC C#  ASP.Net  ASP.NET MVC  Entity Framework 
Ratings:


 1 Reply(s)
 316  View(s)
Rate this:
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.


Anupam Mishra

Total Post:135

Points:949
Posted on    March-28-2016 11:49 PM

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

Modified On Mar-28-2016 11:50:11 PM

Don't want to miss updates? Please click the below button!

Follow MindStick