Click here to Skip to main content
12,349,884 members (24,244 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

48.3K views
56 bookmarked
Posted

WCF 4.5 Services Development with Entity Framework and MVC 4

, 15 Oct 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
WCF 4.5 Services Development using Entity Framework and MVC 4 front-end

Introduction

In this article, I'll be covering the implementation of Windows Communication Foundation (WCF) with Entity Framework (EF) and MVC 4. As far as prerequisites are concerned, I assume that you have some familiarity with the basic Web service and Web application concepts. However, I don't expect you to have any concrete experience using WCF or .NET 4.5. This will cover some of the basics around what it takes to build a simple application using WCF 4.5, with Entity Framework and present the data in the front-end using MVC 4. This application will be using sample database (Northwind), which is widely available on the Internet. The development environment used is Visual Studio 2012. The end result of this application will be displaying the data on an ASP.NET MVC. The service will be exposed and returns a list of ten most expensive products.

Background 

Please note that this is just a demo and a simplified version of a real application. In a real application, you may want to layer your application out. For instance, divide it by separation of concern; such as, Business Data Access, Business Logic, Business Data Object (Entities), and Presentation layers.

Code Use

Let’s begins with creating the WCF service. Below is step by step process of creation of the WCF service:

  1. Open Visual Studio 2012 and run it as an administrator (right click VS2012 and select Run as administrator). This will allow you to run the service that being hosted locally.
  2. Using VS2012, select File | New | Project... to open the New Project dialog window.
  3. In the left panel of the New Project window, select Visual C# | WCF | WCF Service Library as the project template.
  4. Then enter the project name, location, and solution name. In my case, the project name is WcfEfMvcService the location is at C:\Projects\VS2012_Projects\, and the solution I name it WcfEfMvcDemo.
  5. Click OK; Visual Studio will create the project which contains three files: IService1.cs, Service1.cs, and App.config.

EF and Modeling the Northwind Database 

EF and Modeling the Northwind Database The Entity Framework (EF) is designed to separate the process of mapping queries and shaping results from building objects. It allows you to create a conceptual model about the data, build objects, and program against them. Follow the following steps.

  1. Right click WcfEfMvcService project, select Add | New Item, and choose Visual C# Items | ADO.NET Entity Data Model as Template.
  2. Enter NorthwindModel.edmx as the name.
  3. Select Generate from database, choose the existing or create new Northwind connection, and click Next.
  4. Select Next again after having connection value filled in.
  5. Select expend the Tables objects and select the Product table, and then click Finish.

Creating the Service Interface and Operation Contract

The IService1.cs created on the above step contains the default service contract. Note that the interface is using the System.Runtime.Serialization, so now we have a type that we can use within the service operation.

Before we start working on the interface and its implementation, let’s create a class that will hold the data returned from the database. We will name this class ProductEntity.cs. It contains three members that we need for this purpose. We add the set and get properties, in case you need both read and write access to this class in the future. The ProductEntity class should look like this:

Now, let’s work on the Interface and its implementation. First, rename the IService.cs to IProductService.cs and rename the Service.cs to ProductService. Now your solution should look like the image, below:

Below are the steps to create the interface and the service implementation.

  1. Open the IPoductService.cs and delete the existing Operation Contract and replace it with List<productentity> GetTenMostExpensiveProducts();. This service contract describes which operations the client can perform on the service. Your interface class should look like this:
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    
    namespace WcfEfMvcService
    {
    ////Describes which operations the client can perform on the service
    [ServiceContract]
    public interface IProductService
    {
        [OperationContract]
        List<productentity> GetTenMostExpensiveProducts();
    }  
    }
  2. Now, we will work on the implementation. Open the ProductService.cs. We only need to create one LINQ to Entities statement and everything else is handled by LINQ to Entities. The code is clean and it’s strongly typed. LINQ to Entities translates the underlying SQL statement and pass it to the database. It’s very flexible for more granular control. The following code will return the ten most expensive products. Your ProductService class should look like this:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    namespace WcfEfMvcService
    {
    public class ProductService : IProductService
    {
    public List<productentity> GetTenMostExpensiveProducts()
    {
        using (NorthwindEntities db = new NorthwindEntities())
        {
            var query = (from pro in db.Products
                         select new ProductEntity()
                         {
                             ProductName = pro.ProductName,
                             QuantityPerUnit = pro.QuantityPerUnit,
                             UnitPrice = pro.UnitPrice.Value
                         }).OrderByDescending(x => x.UnitPrice).Distinct().Take(10); ;
    
            return query.ToList();
        }
    }
    }
    }

Now, your service is ready to run. However, before you run the service, let’s review the App.config, where it defines the address, contract, and the binding. Make sure all instances of Service1 is replaced with ProductService. Your App.config should look like this:

If you run your service by pressing F5 or clicking the Run button of Visual Studio toolbar, you should see the application running successfully, as seen on the following screenshot. You will see one method in the list, GetTenMostExpensiveProducts(). When you invoke this method, you will see the response at the bottom panel. You can also see the SOAP Request and Response if you click the XML tab at the bottom.

Wring the client and Consuming the WCF Service

For this demo, we will use ASP.NET MVC to consume the service. You can also consume the service with other approaches; such as Widows forms, WPF, Windows service, or even other technologies, like Java and many more.

To create the front-end client using MVC, do the following:

  1. Right click the WcfEfMvcDemo solution, and Add | New Project…
  2. In the Add New Project window, select Web on the left panel and then select ASP.NET MVC 4 Web Application.
  3. Name the project WcfEfMvcClient and click OK.
  4. Select Internet Application as a project template and then click OK.
  5. Now the MVC 4 project is added to the solution and you should see several of folders created by default when selecting the Internet Application as a template project.
  6. Let’s add reference to the WcfEfMvcService class because we will need to use the ProductEntity class.
  7. Right click on the References under the WcfEfMvcClient project and select Add Web Service References…
  8. When the Add Service Reference window shows up, click the Discover button or type the service address in the textbox. You can name the service reference as you choose or leave it as default (ServiceReference1).
  9. On this step, you can create your own controller, but for this demo, let’s use the HomeController. Open the HomeController.cs and add the using statement (using WcfEfMvcService;)
  10. In order to consume the service, we need to instantiate the Service Reference, like this, ServiceReference1.ProductServiceClient obj = new ServiceReference1.ProductServiceClient();
  11. Create a method call Product that returns an ActionResult. Your Home Controller should look like this:
    using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
            using System.Web.Mvc;
            using WcfEfMvcService;
            namespace WcfEfMvcClient.Controllers
            {
            public class HomeController : Controller
            {
            ServiceReference1.ProductServiceClient obj = new ServiceReference1.ProductServiceClient();
            public ActionResult Product()
            {
            List<productentity> productOrders = new List<productentity>();
        productOrders = obj.GetTenMostExpensiveProducts().ToList();
        return View(productOrders);
    }
    
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
    
        return View();
    }
    
    public ActionResult About()
    {
        ViewBag.Message = "Your app description page.";
    
        return View();
    }
    
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
    
        return View();
    }
  12. In this step, we will to create a view. Right click the Home Views and select Add | View…
  13. In the Add View window, type the name as Product, check the Create Strongly-Type view and use the ProductEntity (WcfEfMvcService) and the Model Class.
  14. Open the Product.cshtml and changes the first line to @model IEnumerable<wcfefmvcservice.productentity>. This will allow you to loop through the IEnumerable collection of the Produce Entity.
  15. Use the foreach loop to iterate through the Model defined above. You code in the Product.cshtml should look like the following:
  16. Set the WcfEfMvcClient project as the startup project, and run the application. The end result should look like the screenshot, below:

Summary

That brings us to the end of this article. We've seen that WCF, EF, and MVC are working nicely together. The WCF fits within public web facing service scenarios where you need a high degree of scalability and interoperability. The good news is WCF provides a programming model that accommodates each of these different styles and a variety of different message formats. EF allows developers to have most of the data-access code that we usually need to write. And MVC is very robust pattern that gains more popularity in the recent years. So, there's only one way to write the code, but a lot of different ways to wire things up.

License

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

Share

About the Author

Balimusi
Software Developer (Senior) Agile Tech Consulting, LLC
United States United States
Nengah Mustika started developing software in 2001. He earned his B.S. with double major in Computer Science and Business Administration from Shepherd University in 2004, and M.S. in Computer Science from University of North Florida in 2007.

Mustika is Microsoft Certified Professional Developer (MCPD .NET 4), Microsoft Certified Technology Specialist (MCTS .NET 2.0), both developing and implementing web, server and desktop applications with C#/.NET, MCTS in MOSS 2007 Implementation and Configuration, and CompTia N+ and A+ certified.

He worked at Idea Integration located in Jacksonville, FL as a .NET/BI Consultant from December 2004 – January 2014. On July 30, 2013, he founded an IT consulting firm named Agile Tech Consulting, LLC (a.k.a ATC). In February of 2014, Mustika joined forces with ATC to realize the vision of training the next generation of software developers and delivering excellence in every facet of the Software Development Lifecycle. Visit ATC at www.agiletechconsulting.com

You may also be interested in...

Comments and Discussions

 
QuestionGreat project to do TY on this one Pin
Member 1149264922-Apr-15 5:55
memberMember 1149264922-Apr-15 5:55 
QuestionWhat is that WcfEfMvcService.ProductEntity.datasource file?? Pin
Member 1139863110-Feb-15 1:35
memberMember 1139863110-Feb-15 1:35 
QuestionUpdates Pin
kiquenet.com7-Nov-13 21:03
memberkiquenet.com7-Nov-13 21:03 
AnswerRe: Updates Pin
Balimusi9-Nov-13 8:49
professionalBalimusi9-Nov-13 8:49 
GeneralRe: Updates Pin
kiquenet.com10-Nov-13 8:48
memberkiquenet.com10-Nov-13 8:48 
GeneralRe: Updates Pin
Balimusi10-Nov-13 9:32
professionalBalimusi10-Nov-13 9:32 
GeneralRe: Updates Pin
Balimusi10-Nov-13 9:34
professionalBalimusi10-Nov-13 9:34 
GeneralMy vote of 5 Pin
750315-Oct-13 6:10
member750315-Oct-13 6:10 
QuestionGetting Error when I run apllication Pin
Member 1020768713-Aug-13 9:49
memberMember 1020768713-Aug-13 9:49 
AnswerRe: Getting Error when I run apllication Pin
Balimusi16-Aug-13 14:31
professionalBalimusi16-Aug-13 14:31 
QuestionWhat if we want to use Data Annotations in this same entity? Pin
suhani261-Aug-13 21:06
membersuhani261-Aug-13 21:06 
AnswerRe: What if we want to use Data Annotations in this same entity? Pin
Balimusi3-Aug-13 8:57
professionalBalimusi3-Aug-13 8:57 
QuestionServiceReference is not referenced in the Client Project Pin
c_4less28-May-13 15:49
memberc_4less28-May-13 15:49 
QuestionServiceReference is not referenced in the Client Project Pin
c_4less8-May-13 21:29
memberc_4less8-May-13 21:29 
AnswerRe: ServiceReference is not referenced in the Client Project Pin
Balimusi9-May-13 4:40
professionalBalimusi9-May-13 4:40 
GeneralRe: ServiceReference is not referenced in the Client Project Pin
c_4less9-May-13 5:31
memberc_4less9-May-13 5:31 
GeneralRe: ServiceReference is not referenced in the Client Project Pin
Balimusi9-May-13 5:36
professionalBalimusi9-May-13 5:36 
AnswerRe: ServiceReference is not referenced in the Client Project Pin
Member 165621416-Jun-13 12:09
memberMember 165621416-Jun-13 12:09 
GeneralRe: ServiceReference is not referenced in the Client Project Pin
Balimusi16-Jun-13 16:02
professionalBalimusi16-Jun-13 16:02 
QuestionDownload Source Code Pin
Balimusi7-May-13 7:24
professionalBalimusi7-May-13 7:24 
GeneralNice article, Nice model. Pin
justweiwei5-May-13 15:10
memberjustweiwei5-May-13 15:10 
GeneralRe: Nice article, Nice model. Pin
Balimusi7-May-13 7:25
professionalBalimusi7-May-13 7:25 
Generalnice article Pin
rajkaty30-Apr-13 0:18
memberrajkaty30-Apr-13 0:18 
GeneralRe: nice article Pin
Balimusi7-May-13 7:26
professionalBalimusi7-May-13 7:26 
GeneralMy vote of 5 Pin
hoang1421429-Apr-13 17:26
memberhoang1421429-Apr-13 17:26 
Questionnice tutorial Pin
gicalle7523-Apr-13 20:23
membergicalle7523-Apr-13 20:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160621.1 | Last Updated 15 Oct 2013
Article Copyright 2013 by Balimusi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid