Ishraq Ahmad
Blog for .net Architects & Developers looking to learn WPF, Silverlight, WCF and ASP.net MVC.
WCF with Entity Framework Tutorial
Microsoft always provides efficient, flexible and faster tools for developers. Windows Communications Foundation (WCF) for instance, can be developed using Entity Framework in 2 minutes. You’re a skeptic? Take a look at following simple tutorial and you will see how quickly you can build ready to use WCF with Entity Framework. In following tutorial, I am using AdventureWorks database. You can download complete source code from here AdventureWorksWCF. Let’s get started,
- Open Visual Studio 2010 and click on New Project. Select ASP.net Web Application as project type and click OK.

- Select Project from Solution Explorer, right click and from Add menu select New Item.

- From Add New Item menu, select ADO.NET Entity Data Model. Give descriptive name and press Add button.

- Select Generate from Database and press Next button in Entity Model Wizard window.

- Create New Connection or select Existing Connection from connection dropdown. Press Next button to continue.

- For simplicity, we are selecting three tables which are Address, Contact, and ContactType. But, you can choose any number of tables according to your requirements. Press Finish to complete wizard.

- Compile the project and make sure there are no compilation errors. At this point, we have successfully added Entity Model. Let’s add WCF Data Service in our project.
- Again, select project, right click and from Add menu
select New item. - From New Item window, select WCF Data Service and press Add button after providing descriptive service name which is AdventureWorksService in our case.

- Visual Studio automatically opens AdventureWorksService.svc.cs file with comments how to link WCF Data Service with Model.

- Replace highlighted /* TODO: put your data source class name here */ with Entity Model name which will be AdventureWorksEntities in this case.
- By default, WCF services are secured. We need to add some code so we can access data unrestrictedly. Inside IntializeService method, add following code,
config.SetEntitySetAccessRule(“*”, EntitySetRights.All);
-
The modified code will look like this,

-
That’s it. Now, you are ready to consume WCF Service Data. Press F5 and run project. You see following output,

- Now, you can access your entities by typing names of entity in URL. For example,
http://localhost:58638/AdventureWorksService.svc/Addresses
http://localhost:58638/AdventureWorksService.svc/Contacts
http://localhost:58638/AdventureWorksService.svc/ContactTypes
You can download complete source code from here AdventureWorksWCF. If you have questions please don’t hesitate to contact me.
Related posts:
Tags: Entity Framework, WCF, WPF
You can be an excellent teacher!!!
Job Well Done =)