Exposing Large Data Models via OData and WebAPI - asp.net-mvc

I have an EF model with about 200 tables, 75 of which I'd like to expose via REST in an MVC app. I started by adding a WCF Data Service (WCF-DS), pointed it to the EF context, and bam, I had the entire database mapped to REST URI's with full OData syntax support in about 2 minutes.
Next I tried to create the same REST URI space with WebAPI. When I tried to add a WebAPI OData Controller the first thing it asks for was a Model Class and when I was done creating the controller (and copying all the required ODataConventionModelBuilder code into the WebApiConfig) I only had one REST endpoint! My impression now is that WebAPI is not well suited to expose entire EF models with a lot of brute force.
So my questions:
Am I missing a way to map a bunch of WebAPI endpoints to a EF model in one fell swoop?
(Maybe T4 templates that build all the WebAPI code when I generate my EF model??)
Are there any compelling reasons to consider WebAPI vs WCF-DS to expose large URI domains?
(Some say that the benefits of WebAPI are to have fine grained control over each and every MVC/HTTP request but that seems counter-productive if the goal is to conform to the OData spec. I'm not sure I want to have 75 controllers and 1000's of lines of code that would tempt my dev colleagues to change one entity's behavior that would result in different behavior from other entities.)
(For cross cutting concerns such as security, caching, or performance throttling WCF-DS seems to have sufficient configure-ability with Interceptors and its DataServiceConfiguration class. Are there any features of WebAPI that would do better here?)
Thanks.
Update: I found this article by Julie Lermon that helps a bit: http://msdn.microsoft.com/en-us/magazine/dn201742.aspx

Since I have only exposed EF model using WCF DS, I can't comment on Web API questions. But we never really had a reason to replace WCF DS with Web API for our model because as you also noticed, EF and WCF DS play so nicely together that you basically get an OData feed for free. On a client side the situation is different: we started with WCF Data Services Client that is trying to mimic Linq to Entity Framework, but is has so many limitations that I ended up writing my own OData client (you can read about what made us unhappy with WCF DS client part here).
Coming back to server side: our domain was large, we had 80+ tables with almost 1000 columns. And we even supported all CRUD operations using batch updates (OData analog of transactions). While I would recommend to think twice before exposing database record update operations over OData protocol due to design principles, we haven't had any technical issues with that approach.

It is my opinion that Web API + OData extensions is highly overrated for a large majority or use-cases, and my argument is that OData is fundamentally data-oriented while Web API has come to become a great fit for general-purpose APIs, which include service-oriented APIs.
Your use-case is, I believe, a prime example of a very data-oriented layer since you don't seem to want to add much domain logic on this tier (server-side of this HTTP API). And WCF-DS works great for that, especially if you're merely wrapping an EF model which does 90% of the work for you (as you've already observed).
Of course it would be a different story if you were modeling more intricate processes at that layer (in that tier), so exploring both options like you did is always a very good idea. Normally the obvious choice should come naturally, either you'll be writing a lot of redundant code with Web API (go with WCF-DS) or you'll be fighting with WCF-DS's very rigid framework by playing with odd entities and not-very-RESTful OData actions (go with Web API alone).
Web API with its OData extensions stands somewhere in the middle, although it's not always clear what advantages it provides over custom WCF-DS providers. I guess it's nice for people who already know Web API or ASP.NET MVC, and may be a requirement if you want open source. I personally wouldn't debate on this technology with technical arguments, except for the few gotchas one should know about (but which have nothing to do with its design). I've ranted about all of this a while ago, should you want more, but I stress again that there are no hard truths in any of this -- discussing architecture and design is in no-trivial proportions a matter of opinions.
Update: WCF-DS was killed.

Related

Does it make sense to separate Rails API and Rails app?

I have a project that involves both mobile and web clients. The mobile clients will mainly get content and post user updates, while the web client is mainly for creating content. As such, the web client and API share a lot of the same models and validation.
I am trying to decide the best approach in this case:
JSON-only Rails API + separate Rails web client that calls API.
Single Rails app with separation of API and client side (somehow).
The pro for me in terms of option N°1 is the separation of concerns, as I can work on the API while someone else do the web client. The con seems to be lots of duplicated code in terms of validation.
N°2 could make more sense in terms of reducing code duplication but it would get messy if more than one person is working on the same code base and setting up a process to resolve code conflicts is not something I want to do at this point since we're an early stage startup and want to get out something quickly.
Is there anything I'm missing?
The best practice is use ONE rails application for API and Web Interface
To separate those parts, just create a namespace for API like it's described there http://collectiveidea.com/blog/archives/2013/06/13/building-awesome-rails-apis-part-1/
Do it in one.
The con seems to be lots of duplicated code in terms of validation.
No, you would not have duplication the validation happens in the model, which is shared by your API <=> web controllers. Of course, you will have separate implementations for the actual authorization/session handling (if you have those), but these will not likely be duplicate but a bit different for your two access layers.

Using breeze js not to interact directly with DBContext

I'm very new with breezejs and having a few questions.
I think that breezejs has very nice features so I can replace my own datacontext. However, I don't want breezejs to interact directly with the dbcontext layer. In fact, in my application, the Service layer only exposes ViewModels - not even the real Business models - to the Controllers . So i'm not so sure whether I can use Breeze or not, since in few Breeze's examples, I only saw Breeze interact directly with DBContext.
Thanks.
=========================================
Thanks Ward for the answer,
About the features that I like from Breeze is that it will help to reduce a lot of time to build my own client-side view models. And to build a SPA, maintaining client-side view models is really painful for me, especially my application have desktop app client and other hand-held device's apps as well. Also, to handle the mapping from a JSon object to Knockout - which means with each view models, I will need a mapper as well.
Currently, my architecture is like this:
Server-side:
Repository layer <=> Service layer <=> Controllers (with the Web API that exposes to Client-side)
Controllers only can get the data (in format of a View Model) by sending request through Service.
So, my question is whether it is possible to make use of Breeze to query and also its integration with knockout.
Breeze never works directly with your DbContext; it works with the service model that you expose through endpoints on your service (e.g., Web API controller methods). But you certainly get the most value from Breeze when the client can query and save entities that are structurally the same as entities on the server.
You can retrieve ViewModels with Breeze - you can call almost any HTTP service method with Breeze. It's not clear to me how Breeze would help you manage those ViewModels on the client once you had retrieved them.
What features of Breeze seem "very nice" to you? Your answer to that question will help you determine if Breeze can be helpful with your preferred architectural style.
Querying data through Breeze without API controllers using DBContext directly should be no problem, saving might be harder but still manageable. I think the most complicated part is to get metadata to the client.
According to this SO answer, samples for exposing metadata from other sources that DBContext directly should be out in a week or so.
Meanwhile, check BreezeJS spa-template sample as there is repository pattern involved on the server side which makes it similar to your data access setup.

Is it a good practice to use an MVC application's own Web API for Ajax bindings?

I'm writting an application that has many Ajax widgets (Kendo-UI to be percise). It's starting to get messy to have all those Ajax responses without the standard controllers so I was starting to consider making each entities their own controller. If I'm taking the time to do this, I figured I might as well go foward and do those as WebAPIs since I was planning to do this in a not so close future, but hey, it would be done already...
So my question is: Is it a good practice to use an MVC application's own Web API as a Ajax Widget feeds or is there any reason to stick with standard Controllers?
I've seen some arguments about performance, but I don't think this applies to this situation. I believe it was more of a "Controller calling WebAPI" situation which has obvious performance hits. But since it's already a client side Ajax call, weither it goes into a standard MVC Controller or a WebAPI controller shouldn't change a thing, would it?
Edit
Additional information regarding the project:
I am using Entity Framework for the data access.
I have a repository pattern going on with UnitOfWork.
I am using proper a MVC structure (EF POCOs AutoMapped to DTO POCOs in the repository and fed into View Models by the controllers)
This is a MVC 4 project on .NET 4.0
There is a lot of database relationships (specially for the object I'm working with at the moment)
I don't know about "good practice", but it's certainly not "bad practice". I see no difference whether you do it in the app or a different one.
I think its a good thing but only if what you are doing in the API is kept as generic as possible to other applications and services can reuse the API.
Both the applications I have written and continue to maintain use pretty much the exact same stack as your app.
I have recently re-factored one of the applications to use the API for all the common things like lists that I'm binding to Kendo ComboBoxes etc. in my views. Its a fairly large application that re-uses a lot of the same lists such as states, priorities, complexities across various Entities and views so it makes sense to put those in the API.
I haven't gone as far as going the whole hog through. I draw the line with things like this:
public ActionResult GetAjaxProjectsList([DataSourceRequest]DataSourceRequest request)
{
return Json((DataSourceResult)GetProjectsList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
That is very specific to how the Kendo Grid wants the data back. Nothing else I have connecting to this app will use this data in this format so I keep it in the controller.
In short... I use the API for common things within the same MVC app and things that I allow to be used by other applications or services, like Excel.

Should I add WCF to my ASP.NET MVC site to feed data to mobile apps?

[I've never used WCF before. I've been googling for a couple days and haven't found any info that makes my decision of whether or not to use it obvious to me.]
I've been developing a website using ASP.NET MVC, LINQ to SQL, and SQL Server.
Now I want to develop some mobile apps which will be fed data from the site's DB.
It has been suggested to me that I use WCF for this.
I know that if I have data facing the public internet, it can be scraped if someone really wants it, but I'd like to minimize the "scrapablility" of my data.
Since my mobile apps will probably just be sending/receiving data in JSON format, what benefits would I get from using WCF instead of just RESTful JSON-returning URI's in MVC?
And if I do implement WCF, should my MVC site be hitting those services for data also instead of using LINQ in my controllers?
I've got an ASP.NET MVC application hitting WCF. I originally developed it without WCF by having the controllers interact with a service layer that hits my repositories. A requirement came up during development that required me to physically separate the UI from the service layer.
Adding WCF was a pain in the rear. Things that worked without WCF no longer worked afterwards. For example, the state of my entities was lost upon transmission to/from the service layer making it very difficult to utilize certain features of my ORM (NHibernate). I could no longer retrieve an entity, map a viewmodel to the entity in my controller, and allow NHibernate to determine whether or not an update was necessary.
That said, the challenges associated with WCF were mostly incurred at the beginning. I don't need to revisit the configuration very often and I've gotten used to working with detached entities. I also have the benefit of physical separation and WCF is extremely flexible.
Would I use WCF if I needed web services but not the separation? I really don't know. I would probably try to make JSON action methods work because those are much easier (not to mention more fun). Keeping it simple is still a wonderful principle.
As for your MVC site hitting services? I think it's safe to say that your action methods should be very thin and there should be very little business logic or persistence concerns within your MVC project. Separation of Concerns makes it much easier to adapt and change your application.
I don't see any need for WCF. I'd consider an API area, or controller if the API is small, and deliver the data via JSON from a controller action. I'd refactor the app so that the API and your controllers use the same repositories. If you need to retrieve data via AJAX from your views, you can use the API, but I don't see any point in your controllers using them if they can take advantage of the repositories.

Is there an advantage to using WCF to facilitate AJAX calls?

I am currently reading through a proposal, where this person is proposing to use WCF services to facilitate AJAX calls in a web application. They say that WCF can serialize data more efficiently.
I personally have never considered going this approach. I have always liked calling MVC controllers using jQuery's AJAX functionality, and that has never been a problem.
Now there is this proposal to use WCF for AJAX, and i'm a little sceptical. I would like to keep and open mind. To me it seems to add another layer, unnecessarily complicating things. Is this worth it?
As a side note, ASP.Net MVC currently uses the JavaScriptSerializer (even though it has been marked as obsolete post .Net 3.5) for serializing JSON data where WCF uses the DataContractJsonSerializer.
So in terms of JSON serialization efficiency, MVC will be more efficient as the JavaScriptSerializer is alot more lightweight (all be it quick and dirty) than the DataContractJsonSerializer.
HTH
+1 I'm a little sceptical too. I don't think the average punter sends large amounts of data across Ajax/jQuery and if they are I think they need to refactor a little.
So if that is the case then what possible gain could you get from using WCF over normal mvc functionality when you are serializing (maybe) 2 or 3 k of data. I think even 2k is a lot to be sending via Ajax.
Using WCF in the code behind would be a good idea but for ajax serilization, dunno about that one.
I wouldn't bother with a another layer, especially not WCF, to facilitate AJAX calls. If you're already using MVC, the JsonResult will do fine (and according to Jason Fox above, more efficient).
Unless you need a web service for operations that require a web service (i.e. interacting across the web) why bother? An MVC Controller has always done the job for me without the annoying overhead.
It'd be worth it if you're exposing the same services over additional endpoints with different bindings, but if you're just using AJAX then I'd go with an MVC controller that returns JsonResult. You can still get parameter serialization using action filters.
Unless there's specific required functionality that only WCF provides thenan MVC controller will be simpler. You won't have to worry about contracts, bindings, configuration, WCF's JSON formatting, etc.
It sound interesting in concept, but at the end of the day won't you still be returning Json? Maybe I'm missing something, but how can the Json being returned by WCF be more optimized than the Json being returned by WCF? It's like saying my XML is more optimized than yours? It's not like WCF can return binary data to the browser - you would have no way of using that data... (Or can it??) I suppose the WCF serializer could possibly be faster than the MVC one, but the bottleneck is always going to be getting this data across the wire.
Of course this is all pure speculation - we would need the proposal you read to give an accurate opinion. And it depends very much on how much data you're sending via Ajax.
WCF has its own serializer, which (IIRC) is binary, and which handles object graphs that XML serialization can't. It also shouldn't have the verbose overhead of XML. As griegs noted, that's probably an excessive concern with optimization.
Is WCF more efficient than JSON? Don't know, not sure it matters that much.
In coding, there would be a thin service layer, and the ASP.NET hosting, so that adds overhead. Whether it affects performance is a separate issue; it's just overhead that's visible, as compared to .asmx or MVC controller overhead for handling services.
I don't think you really gain any of WCF's other capabilities in this case. Using WCF for ASP.NET hosted web services restricts you to a specific binding protocol.
EDIT: Looking at the project where I used WCF for web servces, it is web HttpBinding. As noted in comments, that would be JSON. On the other hand, if you're using the ASP.NET ScriptManager tag, it builds a proxy dynamically that includes parsing the data, so you're really never aware of how the data is serialized.

Resources