OData – The easiest service I can create
Posted
by Jon Dalberg
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Jon Dalberg
Published on Wed, 12 May 2010 10:58:42 GMT
Indexed on
2010/05/12
18:05 UTC
Read the original article
Hit count: 295
I wanted to create an OData service with the least amount of code so I fired up Visual Studio and got cracking. I decided to serve up a list of naughty words and make them read-only.
Create a new web project. I created an empty MVC 2 application but MVC is not required for OData.
Add a new WCF Data Service to the project. I named mine NastyWords.svc since I’m serving up a list of nasty words.
Add a class to expose via the service: NastyWord
1: [DataServiceKey("Word")]
2: public class NastyWord
3: {
4: public string Word { get; set; }
5: }
I need to be able to uniquely identify instances of NastyWords for the DataService so I used the DataServiceKey attribute with the “Word” property as the key. I could have added an “ID” property which would have uniquely identified them and would then not need the “DataServiceKey” attribute because the DataService would apply some reflection and heuristics to guess at which property would be the unique identifier. However, the words themselves are unique so adding an “ID” property would be redundantly repetitive.
Then I created a data source to expose my NastyWord objects to the service. This is just a simple class with IQueryable<T> properties exposing the entities for my service:
1: public class NastyWordsDataSource
2: {
3: private static IList<NastyWord> words = new List<NastyWord>
4: {
5: new NastyWord{ Word="crap"},
6: new NastyWord{ Word="darn"},
7: new NastyWord{ Word="hell"},
8: new NastyWord{ Word="shucks"}
9: };
10:
11: public NastyWordsDataSource()
12: {
13: NastyWords = words.AsQueryable();
14: }
15:
16: public IQueryable<NastyWord> NastyWords { get; private set; }
17: }
Now I can go to the NastyWords.svc class and tell it which data source to use and which entities to expose:
1: public class NastyWords : DataService<NastyWordsDataSource>
2: {
3: // This method is called only once to initialize service-wide policies.
4: public static void InitializeService(DataServiceConfiguration config)
5: {
6: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
7: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
8: }
9: }
Compile and browse to my NastWords.svc and weep with joy
Now I can query my service just like any other OData service. Next time, I’ll modify this service to allow updates to sent so I can build up my list of nasty words.
Enjoy!
© Geeks with Blogs or respective owner