How to join linq query in ASP.NET MVC

Total Post:154


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


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. 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


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.