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:
- 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.
- Using VS2012, select File | New | Project... to open the New Project dialog window.
- In the left panel of the New Project window, select Visual C# | WCF | WCF Service Library as the project template.
- 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.
- 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.
- Right click WcfEfMvcService project, select Add | New Item, and choose Visual C# Items | ADO.NET Entity Data Model as Template.
- Enter NorthwindModel.edmx as the name.
- Select Generate from database, choose the existing or create new Northwind connection, and click Next.
- Select Next again after having connection value filled in.
- 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.
- 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
{
[ServiceContract]
public interface IProductService
{
[OperationContract]
List<productentity> GetTenMostExpensiveProducts();
}
}
- 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:
- Right click the WcfEfMvcDemo solution, and Add | New Project…
- In the Add New Project window, select Web on the left panel and then select ASP.NET MVC 4 Web Application.
- Name the project WcfEfMvcClient and click OK.
- Select Internet Application as a project template and then click OK.
- 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.
- Let’s add reference to the
WcfEfMvcService
class because we will need to use the ProductEntity
class.
- Right click on the References under the WcfEfMvcClient project and select Add Web Service References…
- 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
).
- 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;
)
- In order to consume the service, we need to instantiate the Service Reference, like this,
ServiceReference1.ProductServiceClient obj = new ServiceReference1.ProductServiceClient();
- 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();
}
- In this step, we will to create a view. Right click the Home Views and select Add | View…
- 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.
- 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.
- Use the foreach loop to iterate through the Model defined above. You code in the Product.cshtml should look like the following:
- 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.