65.9K
CodeProject is changing. Read more.
Home

Joining Table and Display Data using WCF Service in MVC

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (3 votes)

Dec 21, 2014

CPOL
viewsIcon

15183

How to join table and display data using WCF Service in MVC

  1. Create a new Webapplication in MVC.

  2. Create a new database and add two tables which are department_table and employee.

    In Employee table, Did field is foreign key of Department_table.

  3. Now add entity model in website.

  4. In which choose employee and department_table.
  5. Add new Class in which write this field that you want to display in website.

  6. Add WCF Service to website and in Iservice.cs file, write this code:
        [OperationContract]
        List<Class1> getdata();
  7. In Service.cs file, write this code:
        DatabaseEntities obj = new DatabaseEntities();
      
        public List<Class1> getdata()
        {
            var x = from b in obj.Employees
                    join a in obj.Department_table
                           on b.Did equals a.Did
                    select new Class1 { Name = b.Name, 
                        Address = b.Address,
                        Department = a.Department };
            return x.ToList();
         }
  8. Now Run Service. Then add other MVC website in which also add class which is previously added in website.
  9. Add ServiceReference and in home controller, add this code:
           ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
            public ActionResult Index()
            {           
                var x=obj.getdata();
                var y = x.ToList();
     
                  var data = new  List<Class1>();
    
                  foreach(var item in y)
                  {
                     data.Add(new Class1 
                     {
                        Name = item.Name,
                        Address=item.Address,
                        Department=item.Department
           
                     });
                  }
    
              return View(data);
            }
  10. Output of this code is as follows: