HOW TO JOIN LINQ QUERY IN ASP.NET MVC

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
 891  View(s)
Ratings:
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.
  1. Anupam Mishra

    Post:135

    Points:949
    Re: How to join linq query in ASP.NET MVC

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!