How to Create OData Service in ASP.NET

In this article, you will learn how to create an OData Service in ASP.Net.

First of all start Visual Studio and create a new website and provide the name and location and click "Next" then click on "Add new item" and select "ADO.NET Entity Data Model" from installed templates and click "Add".

img1.jpg

Image 1.

And the next step is to choose "Generate from database" and click the "Next" button and after that choose your data connection.

img2.jpg

Image 2.

Now select table names and objects and click "Finish".

img3.jpg

Image 3.

Now right-click on the solution and click on "Add new item" and select "WCF Data Service".

img4.jpg

Image 4.

This is the default class code.

 

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

 

You need to make a few changes like the following:

 

  1. public class CustomersService : DataService<NORTHWNDEntities1>  
  2. {  
  3.     // This method is called only once to initialize service-wide policies.  
  4.     public static void InitializeService(DataServiceConfiguration config)  
  5.     {  
  6.         // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.  
  7.         // Examples:  
  8.         config.SetEntitySetAccessRule("Customers", EntitySetRights.AllRead);  
  9.         // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);  
  10.         config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;  
  11.     }  
  12. }

Now right-click on the service and click on "View in browser".

This XML file does not appear to have any style information associated with it. The document tree is shown below.

  1. <service xml:base="http://localhost:5376/CustomersService.svc/">  
  2.   <workspace>  
  3.     <atom:title>Default</atom:title>  
  4.     <collection href="Customers">  
  5.       <atom:title>Customers</atom:title>  
  6.     </collection>  
  7.   </workspace>  
  8. </service> 


Similar Articles