Consuming WCF Service In MVC Application Using Entity Framework

This article includes a step by step tutorial to learn WCF using MVC in Visual Studio. We are also using the Entity Framework (.edmx model) for database operations. This scenario targets the user of Entity Framework Model's first approach that consumes WCF service which is consumed in MVC applications for CRUD operations.

Note :

  1. Make sure that Entity Framework is already installed with Visual Studio. Otherwise, install it using NuGet Packages.
  2. Create a table in your database with the name of "UserDetail", as the following.

     Id  int
     Name  Nvarchar(250)
     Email  Nvarchar(250)

    table

Step 1. Crate a blank solution

  • Open Visual Studio.
  • File - New - Project…
  • Select "Other project Type" in the left pane and choose "Blank Solution."
  • Type the name of the Solution "MvcWcfEF";

    MvcWcfEF

Step 2. Creating an WCF Application

  • Right click on the MvcWcfEF solution in Solution Explorer and go to Add  New Project.

    WCF Application

  • Select WCF Service Application Library and type the name as WcfServiceApp.
  • Click on OK.

    WCF Application

Step 3. Creating a service for CRUD operation.

  • Right click on the WcfServiceApp project and select Add - New Item.
  • Choose Web option from left pane and select "WCF Service".
  • Type the name as "MyService.svc" and click on Add button.

    service

Step 4. Creating an Entity Framework Model.

  • Right click on the WcfServiceApp project and select Add - New Item.
  • Choose Data option from left pane and select "ADO.NET Entity data model".
  • Type the name as "EntityModel.edmx" and click on Add button, same as in the following images.

    Entity Framework Model

    Entity Framework Model

    Entity Framework Model

  • Select your database and type the name of connection settings in web.config as "TestDBEntities".

    TestDBEntities

Step 5. Write a service for CRUD operation

  1. Open MyService.csv page from WcfService application and write the following code:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Linq;  
    5. using System.Runtime.Serialization;  
    6. using System.ServiceModel;  
    7. using System.Text;  
    8.   
    9. namespace WcfServiceApp  
    10. {  
    11.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MyService" in code, svc and config file together.  
    12.     // NOTE: In order to launch WCF Test Client for testing this service, please select MyService.svc or MyService.svc.cs at the Solution Explorer and start debugging.  
    13.     public class MyService : IMyService  
    14.     {  
    15.         public void DoWork()  
    16.         {  
    17.         }  
    18.   
    19.         public List<UserDetail> GetAllUser()  
    20.         {  
    21.             List<UserDetail> userlst = new List<UserDetail>();  
    22.             TestDBEntities tstDb = new TestDBEntities();  
    23.             var lstUsr = from k in tstDb.UserDetails select k;  
    24.             foreach (var item in lstUsr)  
    25.             {  
    26.                 UserDetail usr = new UserDetail();  
    27.                 usr.Id = item.Id;  
    28.                 usr.Name = item.Name;  
    29.                 usr.Email = item.Email;  
    30.                 userlst.Add(usr);  
    31.   
    32.             }  
    33.   
    34.             return userlst;  
    35.         }  
    36.   
    37.   
    38.   
    39.         public UserDetail GetAllUserById(int id)  
    40.         {  
    41.   
    42.             TestDBEntities tstDb = new TestDBEntities();  
    43.             var lstUsr = from k in tstDb.UserDetails where k.Id==id select k;  
    44.             UserDetail usr = new UserDetail();  
    45.             foreach (var item in lstUsr)  
    46.             {  
    47.   
    48.                 usr.Id = item.Id;  
    49.                 usr.Name = item.Name;  
    50.                 usr.Email = item.Email;  
    51.   
    52.   
    53.             }  
    54.   
    55.             return usr;  
    56.         }  
    57.   
    58.         public int DeleteUserById(int Id)  
    59.         {  
    60.   
    61.             TestDBEntities tstDb = new TestDBEntities();  
    62.             UserDetail usrdtl = new UserDetail();  
    63.             usrdtl.Id = Id;  
    64.             tstDb.Entry(usrdtl).State = EntityState.Deleted;  
    65.             int Retval = tstDb.SaveChanges();  
    66.             return Retval;  
    67.         }  
    68.   
    69.         public int AddUser(string Name, string Email)  
    70.         {  
    71.             TestDBEntities tstDb = new TestDBEntities();  
    72.             UserDetail usrdtl = new UserDetail();  
    73.             usrdtl.Name = Name;  
    74.             usrdtl.Email = Email;  
    75.             tstDb.UserDetails.Add(usrdtl);  
    76.             int Retval = tstDb.SaveChanges();  
    77.             return Retval;  
    78.         }  
    79.       public int UpdateUser(int Id,string Name, string Email)  
    80.         {  
    81.             TestDBEntities tstDb = new TestDBEntities();  
    82.             UserDetail usrdtl = new UserDetail();  
    83.             usrdtl.Id = Id;  
    84.             usrdtl.Name = Name;  
    85.             usrdtl.Email = Email;  
    86.             tstDb.Entry(usrdtl).State = EntityState.Modified;  
    87.              
    88.             int Retval = tstDb.SaveChanges();  
    89.             return Retval;  
    90.         }  
    91.          
    92.     }  
    93. }  
  2. Now, Open IMyService and write the "ServiceContract" and "DatatContract", as follows.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Runtime.Serialization;  
    5. using System.ServiceModel;  
    6. using System.Text;  
    7.   
    8. namespace WcfServiceApp  
    9. {  
    10.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMyService" in both code and config file together.  
    11.     [ServiceContract]  
    12.     public interface IMyService  
    13.     {  
    14.         [OperationContract]  
    15.        List<UserDetail> GetAllUser();  
    16.         [OperationContract]  
    17.         int AddUser(string Name, string Email);  
    18.         [OperationContract]  
    19.         UserDetail GetAllUserById(int id);  
    20.   
    21.         [OperationContract]  
    22.         int UpdateUser(int Id, string Name, string Email);  
    23.   
    24.         [OperationContract]  
    25.         int DeleteUserById(int Id);  
    26.     }  
    27.   
    28.   
    29.     [DataContract]  
    30.     public class UserDetails  
    31.     {  
    32.         [DataMember]  
    33.         public int Id { getset; }  
    34.         [DataMember]  
    35.         public string Name { getset; }  
    36.         [DataMember]  
    37.         public string Email { getset; }  
    38.       
    39.       
    40.     }  
    41. }  

Service has been completed. Now, build the service.

  1. Press F5 to run the Service.
  2. Copy the Service URL, as shown in following image (localhost:1034/MyService.svc), for creating the reference.

    Service URL

Step 6. Creating an MVC Application

  • Now, right click on the "MvcWcfEF " solution in Solution Explorer, again.
  • Select e New  Project…
  • Select ASP.NET MVC3/4 Web Application.
  • Enter the name of application as "MvcApp".
  • Click on OK.

Adding a Project Priority and setting the reference

  • Right click on the MvcApp and click on add service reference as in he image below.
  • Paste the Copied Service URL in the given address and press Go button.
  • All the services will display, as in the folowing picture. Just give the Namespace as "ServiceRefernce1" and click on OK button.

    ServiceRefernce1

Since WCF service application and MVC application both are in the same solution, we have to build the Service first and then the MVC application in order to consume the service in MVC application. Do the following for that,

  • Right Click on the MvcWcfEF Solution in Solution Explorer and click on properties.
  • Check the "Multiple Startup Project " and set the application priority for WCF and MVC application (WCF service should be first and MVC afterwards), as in the following image.

    Multiple Startup Project

Create a Model

Right click on Model folder and click on Class. Write the class name as "User" and create the following properties.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcApp.Models  
  7. {  
  8.     public class User  
  9.     {  
  10.   
  11.          
  12.             public int Id { getset; }  
  13.              
  14.             public string Name { getset; }  
  15.              
  16.             public string Email { getset; }  
  17.   
  18.     }  
  19. }  
Create a Controller

Right click on the Controller folder and click on add controller. Give the name of controller as "HomeController" and write the following action for CRUD operation.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcApp.Models;  
  7.   
  8.   
  9. namespace MvcApp.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         //  
  14.         // GET: /Home/  
  15.         ServiceReference1.MyServiceClient ur = new ServiceReference1.MyServiceClient();  
  16.         public ActionResult Index()  
  17.         {  
  18.             List<User> lstRecord = new List<User>();  
  19.              
  20.             var lst = ur.GetAllUser();  
  21.   
  22.             foreach (var item in lst)  
  23.             {  
  24.                 User usr = new User();  
  25.                 usr.Id = item.Id;  
  26.                 usr.Name = item.Name;  
  27.                 usr.Email = item.Email;  
  28.                 lstRecord.Add(usr);  
  29.               
  30.             }  
  31.   
  32.   
  33.             return View(lstRecord);  
  34.         }  
  35.   
  36.   
  37.         public ActionResult Add()  
  38.         {  
  39.   
  40.             return View();  
  41.         }  
  42.         [HttpPost]  
  43.         public ActionResult Add(User mdl)  
  44.         {  
  45.   
  46.             User usr= new User();  
  47.             usr.Name=mdl.Name;  
  48.             usr.Email=mdl.Email;  
  49.             ur.AddUser(usr.Name,usr.Email);  
  50.             return RedirectToAction("Index""Home");  
  51.             
  52.         }  
  53.         public ActionResult Delete(int id)  
  54.         {  
  55.             int retval = ur.DeleteUserById(id);  
  56.             if (retval > 0)  
  57.             {  
  58.                 return RedirectToAction("Index""Home");  
  59.             }  
  60.   
  61.             return View();  
  62.         }  
  63.   
  64.         public ActionResult Edit(int id)  
  65.          {  
  66.             var lst = ur.GetAllUserById(id);  
  67.               User usr = new User();  
  68.               usr.Id = lst.Id;  
  69.               usr.Name = lst.Name;  
  70.               usr.Email = lst.Email;  
  71.               return View(usr);  
  72.   
  73.         }  
  74.         [HttpPost]  
  75.         public ActionResult Edit(User mdl)  
  76.         {  
  77.             User usr = new User();  
  78.             usr.Id = mdl.Id;  
  79.             usr.Name = mdl.Name;  
  80.             usr.Email = mdl.Email;  
  81.   
  82.   
  83.             int Retval = ur.UpdateUser(usr.Id, usr.Name, usr.Email);  
  84.             if (Retval > 0)  
  85.             {  
  86.                 return RedirectToAction("Index""Home");  
  87.             }  
  88.             return View();  
  89.         }  
  90.     }  
  91. }  
Creating a View

Creating a view is very simple. Just right click on All action of the controller and click on Add View. The following is the code for all views (Index, Add, Edit). 

Index.cshtml
  1. @model IEnumerable<MvcApp.Models.User>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7.   
  8. @using (Html.BeginForm()){  
  9.     <div>  
  10.         <h2>User Details</h2>  
  11.          @Html.ActionLink("Add User", "Add", "")  
  12.     </div>  
  13.     <div>  
  14.          <table >  
  15.             <tr style="background-color: #FFFACD; text-align:center">  
  16.                 <th style="text-align:left">  
  17.                     Name  
  18.                 </th>  
  19.                 <th style="text-align:left">  
  20.                    Email  
  21.                 </th>  
  22.                 <th style="text-align:left">  
  23.                     Manage  
  24.                 </th>  
  25.             </tr>  
  26.   
  27.             @{  
  28.                 foreach (var item in Model)  
  29.                 {  
  30.                 <tr style="background-color: #FFFFF0">  
  31.                     <td>  
  32.                         @item.Name  
  33.                     </td>  
  34.                     <td>  
  35.                         @item.Email  
  36.                     </td>  
  37.                      
  38.                     <td>  
  39.                         @Html.ActionLink("Edit", "Edit", new { id = @item.Id }) /@Html.ActionLink("Delete", "Delete", new {id[email protected] })   
  40.                          
  41.                     </td>  
  42.                      
  43.                 </tr>  
  44.                 }  
  45.             }  
  46.   
  47.         </table>  
  48.   
  49.     </div>  
  50.      
  51.   
  52. }  
Add.cshtml
  1. @model MvcApp.Models.User  
  2.   
  3. @{  
  4.     ViewBag.Title = "Add";  
  5. }  
  6.   
  7. <h2>Add New User</h2>  
  8.   
  9. @using (Html.BeginForm()) {   
  10.   
  11. <div style="text-align:center">  
  12.   
  13.     <table>  
  14.         <tr>  
  15.             <td>  
  16.                 Name :   
  17.             </td>  
  18.             <td>   
  19.                 @Html.TextBoxFor(m=>m.Name)  
  20.             </td>  
  21.         </tr>  
  22.   
  23.          <tr>  
  24.             <td>  
  25.                 Email :   
  26.             </td>  
  27.             <td>   
  28.                 @Html.TextBoxFor(m=>m.Email)  
  29.             </td>  
  30.         </tr>  
  31.          <tr>  
  32.             <td>  
  33.                 Email :   
  34.             </td>  
  35.             <td>   
  36.                <input type="submit" value="Submit" />  
  37.             </td>  
  38.         </tr>  
  39.     </table>  
  40.   
  41. </div>    
  42. }  
Edit.cshtml
  1. @model MvcApp.Models.User  
  2.   
  3. @{  
  4.     ViewBag.Title = "Edit";  
  5. }  
  6.   
  7. <h2>Edit User</h2>  
  8.   
  9. @using (Html.BeginForm()) {   
  10.   
  11. <div style="text-align:center">  
  12.   
  13.     <table>  
  14.         <tr>  
  15.             <td>  
  16.                 Name :   
  17.             </td>  
  18.             <td>   
  19.                 @Html.TextBoxFor(m=>m.Name)  
  20.             </td>  
  21.         </tr>  
  22.   
  23.          <tr>  
  24.             <td>  
  25.                 Email :   
  26.             </td>  
  27.             <td>   
  28.                 @Html.TextBoxFor(m=>m.Email)  
  29.             </td>  
  30.         </tr>  
  31.          <tr>  
  32.             <td>  
  33.                    
  34.             </td>  
  35.             <td>   
  36.                <input type="submit" value="Update" />  
  37.             </td>  
  38.         </tr>  
  39.     </table>  
  40.   
  41. </div>  
  42. }  
Now, press F5 to run the Application

Hope your Application View will be like the following image.

Apllcation

And , Like following.

Apllcation
Apllcation

 

Up Next
    Ebook Download
    View all
    Learn
    View all