Share via


WCF Data Services with Entity Framework Provider

This Article focuses on  how we can implement a WCF Data Service with Entity Framework Provider.

I have created an empty ASP.NET web application. Now let’s start by adding an ADO.NET Entity Data Model to the project.

http://lh3.ggpht.com/-VruZWO7SVes/UgPPKn-9c7I/AAAAAAAABr0/JGkRUZ4qfDA/image_thumb%25255B1%25255D.png?imgmax=800
ADO.NET Entity Data Model

Now I am asked to create a model with existing database or to create an empty model. I am going with the Empty model, so we can learn all these steps from the scratch.

 

http://lh4.ggpht.com/-5OO5Ti_EduI/UgPPMDuMwuI/AAAAAAAABsE/thFzojga000/image_thumb%25255B2%25255D.png?imgmax=800
Empty Model

I am clicking finish and I am getting an empty model designer. Now let’s create some entities and add some associations.

I am right clicking on the designer and selecting Add New –> Entity called "Employee". I am creating a Key property which is “EmployeeId” and type I am leaving it as it is which is Int32.

http://lh3.ggpht.com/-APhmqOPcpjA/UgPPNTVeBZI/AAAAAAAABsU/eadbuFcUmTk/image_thumb%25255B3%25255D.png?imgmax=800
Add Entity
http://lh4.ggpht.com/-g59Izsxdzq0/UgPPPNJcTpI/AAAAAAAABsk/HkmOohJAg1c/image_thumb%25255B5%25255D.png?imgmax=800
Entity Added

Now I am right clicking on the Employee entity and adding some Scalar Properties which are “FirstName” and “LastName”. From the properties window of these Scalar Properties we can change the things like data type, etc.

Same way I am creating two other entities which are “Department” and “JobRole”. Finally I am getting the following:

http://lh5.ggpht.com/-O8Iv9axzLWc/UgPPQmIn06I/AAAAAAAABs0/CemmLeKvWDQ/image_thumb%25255B7%25255D.png?imgmax=800
Entity Relationship Diagram without Associations

Now let’s create some associations. I am right clicking on the designer and selecting Add New->Association. I am creating a relationship between Employee and Department which is Employee can only belong to one Department and one Department can have many Employees.

http://lh5.ggpht.com/-9scIsSdlj8I/UgPPSJQ1gcI/AAAAAAAABtE/xa208MQirXo/image_thumb%25255B8%25255D.png?imgmax=800
Add Association

Same way I am creating a relationship between Employee and JobRole in which Employee can have many JobRoles and one JobRole can have many Employees.

http://lh6.ggpht.com/-Aj1vCovNFq4/UgPPTmEwImI/AAAAAAAABtU/aXx-p_o0ex4/image_thumb%25255B9%25255D.png?imgmax=800
Add Association

Once this is done I am getting the following model.

http://lh3.ggpht.com/-qo_2RtO4Wx4/UgPPVaT2wgI/AAAAAAAABtk/T9m50PdLICo/image_thumb%25255B11%25255D.png?imgmax=800
Entity Relationship Diagram with Associations

Now let’s right click on the designer and select “Generate Database from Model” to create a database from this model.

I have already created a blank database called “EFProviderDB” and let’s create a connection to this particular database.

http://lh5.ggpht.com/-0eYREQISUvE/UgPPWw4iAUI/AAAAAAAABt0/0n5plMtuyMQ/image_thumb%25255B13%25255D.png?imgmax=800
Choose Data Source
http://lh6.ggpht.com/-9i_SqyVe2Yc/UgPPYNB-y-I/AAAAAAAABuE/p1cCpwPtaxk/image_thumb%25255B14%25255D.png?imgmax=800
Connection Properties
http://lh6.ggpht.com/-B3w_YxkWVUs/UgPPZ5rHHbI/AAAAAAAABuU/pd3JnRq80NU/image_thumb%25255B15%25255D.png?imgmax=800
Generate Database Wizard
http://lh6.ggpht.com/-K5DD3Bljppc/UgPPbuhcVsI/AAAAAAAABuk/6dhWB5olz5c/image_thumb%25255B16%25255D.png?imgmax=800
Generate Database Wizard

OK, now what I have to do is run this query on the SQL Server Management Studio to create my tables and the relationships. After running the query I can see my tables got created and their relationships.

Now let’s add some data to expose via WCF Data Services.

http://lh5.ggpht.com/-FJIWX2vDuKg/UgPPddvsX9I/AAAAAAAABu0/390wS9qxIB8/image_thumb%25255B18%25255D.png?imgmax=800
Tables created in the database

Once the data is added to the tables, I am going to add new project item which is “WCF Data Service”.

http://lh4.ggpht.com/-BUWos0wRJ00/UgPPe-7pqPI/AAAAAAAABvE/hQR4pjF33Jg/image_thumb%25255B20%25255D.png?imgmax=800
WCF Data Service

The Visual Studio will create a service which is of WCF Data Service template.

public class WcfDataService1 : DataService< /* TODO: put your data source class name here */ >
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
        // Examples:
        // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);
        // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
    }
}

 

In simple terms, this is a service class which is derived from DataService of type T. It has a single static method which is InitializeService(…). What this class does is it will expose data in a particular context which is T.

 

Now I am going to modify this class. First I need to find out what the context is. For that I am opening the Model1.Context.cs and I am copying the the class name, in here it’s “Model1Container”. Now this is my data service type.

http://lh5.ggpht.com/-BkKjuuMyn9Q/UgPPgm5X22I/AAAAAAAABvU/GWfbmAvrLL8/image_thumb%25255B22%25255D.png?imgmax=800
Exposing Context

Now I am modifying the InitializeService(…) method as follows. I am setting up a entity access rule for all the entities, so consumers can read all data.

public class WcfDataService1 : DataService<Model1Container>
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
        // Examples:
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
    }
}

 

I can even modify the method in the following way, so only two entities are exposed (“Employee” and “Department”) to outside.

public static void InitializeService(DataServiceConfiguration config)
{
    // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
    // Examples:
    config.SetEntitySetAccessRule("Employee", EntitySetRights.AllRead);
    config.SetEntitySetAccessRule("Department", EntitySetRights.AllRead);
    // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}

 

You can set various rights here and it’s up to you to explore. For this demo I am exposing all the entities.

 

And that’s it. When I run the project I can see my WCF Data Service up and running.

http://lh3.ggpht.com/-QGL0EelYdWA/UgPPiLzDCKI/AAAAAAAABvk/o4Inu66qX14/image_thumb%25255B24%25255D.png?imgmax=800
Up and Running WCF Data Service

Now let’s see how we can consume this data service. I am creating a console application and adding a service reference.

Now I am writing the following code.

using ConsoleApplication1.svcWcfDataService;
using System;
using System.Linq;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Model1Container modelContext = new Model1Container(new Uri("http://localhost:51639/WcfDataService1.svc/"));
            var employees = from e in modelContext.Employees
                            select e;
            foreach (var e in employees)
            {
                Console.WriteLine("{0}, {1}", e.LastName, e.FirstName);
            }
            Console.ReadLine();
        }
    }
}

I am creating a object of my data context. Now I am writing a LINQ query to retrieve the data. Behind the scene the LINQ query is transforming into URL syntax and executes HTTP methods such as “GET”,“POST” etc. based on my request.

I am attaching a sample project to MSDN Code Gallery, you can play around.
   Download Sample

Happy Coding.