Let’s talk about OData.
I would propose to start our OData journey with the best thing about it. Which is openness of data, easy of accessing and working with it. Client applications no longer need to depend on some specific service methods or formats if there is OData feed available. Consuming OData is simple and enjoyable.
For example, I want to know how many users with name ‘Andriy’ are there on StackOverflow with reputation higher than 500. No one at StackOverflow would develop special method in API which would allow me to request exactly this data.
But as StackOverflow exposes OData feed we can connect to it with LinqPad (get it here) and simply write normal C# linq query, like this one:
You can see same data if you use URL below. This URL was built by LinqPad to request data:
(View page source if you don’t like how your browser rendered that feed).
So, no magic. You just build special URL and get your data of interest in preferred format. You can use wide set of libraries both for client and server to implement and use OData.
Whenever you see this icon it is good indication that there is OData feed available. There are many applications/web sites that already utilize this protocol. Do you use Nuget? It works through OData. Know ebay? They expose its catalog via OData. Need more examples? Go to ecosystem page of OData.
The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients and servers in a variety of products over the past several years. OData is being used to expose and access information from a variety of sources including, but not limited to, relational databases, file systems, content management systems and traditional Web sites.
…from http://www.odata.org/
Continue your reading about OData on its documentation page here.
If you have time, I would recommend to watch this “OData: There’s Feed for That” MIX10 video.
As OData was initially introduced by Microsoft no wonder it is extremely easy to put it in place when you are on MS stack of technologies. If you are using EF there is almost nothing you have to do to make it happen.
Add “WCF Data Service” to your project.
You will get following code:
public class WcfDataService1 : DataService< /* TODO: put your data source class name here */ > { // This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) { // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc. // Examples: // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead); // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } }
Assuming that you have your data model generated on Northwind db. All you would need is something like this:
public class WcfDataService1 : DataService<NorthwindContext> { public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.All); config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } protected override NorthwindContext CreateDataSource() { return new NorthwindContext(ConfigurationManager.ConnectionStrings["NorthwindContext.EF.MsSql"].ConnectionString); } }
And now clients can do whatever they like with your data. Of course, you can restrict them as you wish. OData is not about putting your database into web, you can control what you expose and to which extent. Also you can play with your service by adding caching, intercepting queries, changing behaviors and much-much more.
In next post I will show how we can build OData service for custom data you keep in memory.
In meantime you can checkout another video from NDC2011 by Vagif Abilov. Video is called “Practical OData with and without Entity Framework”. Follow this link to direct mp4 video file.
Markdown | Result |
---|---|
*text* | text |
**text** | text |
***text*** | text |
`code` | code |
~~~ more code ~~~~ |
more code |
[Link](https://www.example.com) | Link |
* Listitem |
|
> Quote | Quote |
А что с путями? Оно так и работает на svc темплейте? Или уже на нормальном роутинге как ASP.NET WebAPI (WCF WebAPI)
SVC file is just notion of one of implementations of OData (wcf one). I just started learning OData. If I understood your question, and as far as I know it works this way only out of the box, but I believe you can change this behavior.
Maybe following links could help answer this:
http://blogs.msdn.com/b/rjacobs/archive/2010/04/05/using-system-web-routing-with-data-services-odata.aspx
http://www.gtrifonov.com/2011/06/01/odata-wcf-data-services-friendly-urls-using-routing/
As you can see SO odata link doesn't have ".svc":
http://data.stackexchange.com/stackoverflow/atom/Users(263505)/Badges
Here is information on URI conventions:
http://www.odata.org/documentation/uri-conventions
То что можно изменить URI без svc – само собой. Уже как "100 лет" можно. Вопрос был про MVC роутинг, поэтому за ссылку спасибо (вторая дублируется с ней по сути):
http://blogs.msdn.com/b/rjacobs/archive/2010/04/05/using-system-web-routing-with-data-services-odata.
Хоть оно и не идет с коробки так почему то. Но пиушт что можно легко поменять. Пока не попробую – верю :)
По третей ссылки – так оно само собой разумеется что нормальные сервисы убирают это гадское "svc", опять же "100 лет" как оно так. Один из способов убрать – прикрутить мвц роутинг.
Согласно 4-й ссылке – она не в тему. Ну да OData URI Conventions, но вопрос по поводу роутинга. Там я уже был когда-то :)
Еще вопросик, который меня интересует. Возможно ты знаешь. Меня интересуют перехваты вызовов абсолютно всех из коробки. Как с этим дело обстоит? Насколько сложно или легко? Возможно ты знаешь подводные камни, тогда какие? Понятное дело что если я подкручу свой роутинг на MVC и в своей фабрике или хедлерах смогу перехватить вызовы, но интересует именно из коробки