Use EF and WCF to create a rest json Service. First, we need to download a Visual Studio Template named "ADO. net c # POCO Entity Generator With WCF Support ".
This is mainly used to generate the Model Class of WCF. Because the default EF Template does not have the Annotation [DataMember] or [DataContract.
Create a project in Visual Studio. Create an Entity framework EDMX. Here we have a Table,
As mentioned above, the default template generated in EF 4.0 does not have the Annotation [DataMember] and [DataContract]. Therefore, we need to use a new Template to generate the Model class.
If you open Employee. cs, you will find that there is no [DataContract] in the class and the attribute is not DataMember.
First, delete the automatically generated template and Model class.
First, return to EDMX and right-click Add Code Generation Item...
Select EF 5.x DbContext Generator with WCF Support
After adding the package, let's look at our Employee. cs.
As JSON does not support serialization of IsReference, You need to delete this IsReference if you want to output JSON. if you output xml, the IsReference is okay.
Therefore, we need to go to the template file and delete this IsReference. This is very simple, just take a simple query. Note: In this template, IsReference hasTwo placesRemember to delete all of them.
Basically, the JSON problem on Entity Framework has been completed. Now we write a Service, GetEmployee (int employeID)
First, we create an EmployeeService. svc,
Note that if you use UriTemplate = "employee/{id}", the value of 'employee GetEmployee (int id) 'must be a String id; otherwise, an exception is thrown.
All right, web. config.
There is nothing in webconfig. You only need to add an endpointBehavior <webHttp/>, and then behaviorConfiguration = This endpointBehavior in your service endpoint.
In addition, the binding type of your service endpoint is webHttpBinding.
Remember to add the mexHttpBinding
All web. config is here
The execution result is
Source code Link