Click here to Skip to main content
12,546,962 members (55,225 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


7 bookmarked

REST with WCF and Entity Framework with JSON Serialization

, 12 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
REST with WCF and Entity Framework with JSON serialization.

Problem: you have some database and use Entity Framework to get data from it. You need develop web-service which returns JSON-data based on your entities. And as a consumer of this service you need to use javascript client. Also, you should provide cross-domain access to your web-service.

First, let's define configuration for this service:

    <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
  <service name="[Name of your service]">
    <endpoint address="" behaviorConfiguration="restBehavior" binding="webHttpBinding" 
              bindingConfiguration="crossDomain" contract="[Name of your contract]">
        <dns value="localhost" />
    <behavior name="restBehavior">
      <webHttp />

Parameter crossDomainScriptAccessEnabled="true" allows requests from another domain. If you need to use SSL, just add security tag to the binding tag with mode="Transport":

<binding name="crossDomain" crossDomainScriptAccessEnabled="true">
<security mode="Transport" /></binding>

Okey, now we should define service contract. To get JSON-data from your web-methods you should add WebGet(ResponseFormat = WebMessageFormat.Json) attribute to each web-method:

[ServiceContract]public interface IService1
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string GetOrder(Int32 id);

Now, we can request our service something like this, I use jQuery:

$.getJSON('/GetOrder?id=7&callback=?', function (data) {

Great, but when we try to return entity we get this error:

The type 'xxx' cannot be serialized to JSON because its IsReference setting is 'True'.

Entity Framework doesn't support JSON-serialization, so I found this workaround:

public string GetOrder(Int32 id)
    // getting order…
    return SerializeJSON(order);
static string SerializeJSON<T>(T obj)
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.Serialize(obj);


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


About the Author

Dmitriy Kozlov
Technical Lead Plumsail
Russian Federation Russian Federation
Expert in SharePoint
The leader of SharePoint Forms Designer Team:
Co-founder of Plumsail:
My blog:

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161018.1 | Last Updated 12 Apr 2013
Article Copyright 2013 by Dmitriy Kozlov
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid