Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Joining Table and Display Data using WCF Service in MVC

4.71/5 (3 votes)
21 Dec 2014CPOL 15.2K  
How to join table and display data using WCF Service in MVC
  1. Create a new Webapplication in MVC.

    Image 1

    Image 2

  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.

    Image 3

    Image 4

  3. Now add entity model in website.

    Image 5

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

    Image 6

  6. Add WCF Service to website and in Iservice.cs file, write this code:
    C#
    [OperationContract]
    List<Class1> getdata();
    
  7. In Service.cs file, write this code:
    C#
    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:
    C#
    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:

    Image 7

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)