Choosing a Data Access Layer for Silverlight 3

SilverlightIf you're a regular reader of my blog, you'll probably remember my pithy blog post where I stated that "It all depends..." to the question "Which Data Access Should I Use for Silverlight 3?"  The reality is that much like the similar question I am confronted with at user groups for the past decade ("What data access should I use in my .NET app?"). The reasons for picking a strategy are wide and varied so I will not try to analyze all possible outcomes, but I think the different strategies need to be explained better.

The three major candidates in Silverlight 3 are Web Services (WCF/ASMX), ADO.NET Data Services and RIA Services.  In any situation, any of these will work. But they are suited to different styles and requirements. Here's the abridged differences between the stacks:

  • Web Services: Interface-based Data Access
  • ADO.NET Data Services: LINQ-based Data Access with change management
  • RIA Services: Interface-based Data Access with change management

Let's dive deeper into explaining these differences and why that might matter.

Web Services

Using web services is the tried and true method for communicating across the firewall. This pattern is well known and reliable. In general this requires you specify an interface for the CRUD operations as separate operations on a web service then dutifully call them in your Silverlight code.

Reasons to Use: Any existing investment in web services can be a great reason to use them (whether in code or skillset). Also, web services are often used in cases where a project wants a very close control over the flow from the application to the database.

Reasons to Avoid: With web services you end up having to keep track of the changes yourself and know what services to call with updates. Any need for batching or transactional support gets cumbersome and code-intensive.

ADO.NET Data Services

ADO.NET Data Services is a simple REST-based facility for data access. It relies on the HTTP stack to help define the interface. GET calls become Reads, POST becomes Updates and so on. It uses ATOM or JSON for its serialization format so it is consumable by a variety of clients.

Underneath its covers it takes this URI based API and converts it into a LINQ call for GETs and to API calls to the provider for inserts, updates and deletes. That means that ADO.NET is a thin layer who's purpose is to translate the URI model to data access code.  But its better than that...

The real power of ADO.NET Data Services for Silverlight is the inclusion of the Client Library. This client library allows you to issue LINQ queries defined in the client and executed on the server. While the LINQ syntax is somewhat limited when compared to the server, it fulfills the 80% case and ADO.NET Data Services allows you to add operations to fill in the rest when necessary. In addition, the client library includes a powerful data context class that can monitor changes and issue changes in batches with transactional support.

Exposing your data access with ADO.NET Data Services is about exposing queryable end-points instead of defining an interface. This is what makes is unique. For example, we can query our service using a LINQ Query like so:

// Silverlight Code

// Create the query using LINQ
var qry = (from g in ds.Games
           where g.Price < 50m
           orderby g.Name
           select g) as DataServiceQuery<Game>;

// Execute the Query
// (This part is getting cleaner in ADO.NET Data Services v1.5) 
qry.BeginExecute(new AsyncCallback(r =>
  {
    games2.ItemsSource = qry.EndExecute(r).ToList();
    games2.DisplayMemberPath = "Name";
  }), null);

Reasons to Use: Want a simple, secure model where the developers can define the queries they need in code instead of changing the interface as the needs change.  The ADO.NET Data Services' client library makes the amount of code you write on the client small as it becomes LINQ calls and working with the context class.

Reasons to Avoid: When you want tight control over the interface to your data access and do not want developers issuing LINQ queries directly from the client code.

RIA Services

As the new kid on the block, RIA Services has a lot to offer. RIA Services is based on the idea of creating a data access API on the server and at the same time creating the client code in Silverlight (and other platforms in the future). Its focused on sharing code between the client and the server including validation logic.  In addition, while it allows you to create a set interface, it also provides a context object which can monitor changes on the client and batch those changes back to the server. In some ways RIA Services is like a hybrid of Web Services and ADO.NET Data Services.

Because RIA Services is based on a server-side query defined in its interface, on the client we call the query by calling the call on the interface:

// Silverlight Code

// The context object that tracks changes
XBoxGamesContext ctx = new XBoxGamesContext();

// Our RIA Query, really a call to an interface
var qry = ctx.GetGamesByGenreQuery("Shooter");

// Bind the data
theList.ItemsSource = ctx.Load<Game>(qry).AllEntities;

While in ADO.NET Data Services you are issuing LINQ queries, RIA Services also allow you to add LINQ constraints to the query endpoints.  For example instead of just creating a query by calling the interface, you can add LINQ expressions to the endpoint like so:

var riaQry = ctx.GetGamesQuery()
                .Where(g => g.Price < 50m)
                .OrderBy(g => g.Name);

LoadOperation<Game> op = 
  ctx.Load<Game>(riaQry);

Reasons to Use: RIA Services is a good choice if you expect to develop a straightforward application minimum number of tiers. It works best in Rapid Application development scenarios versus large architected applications. RIA Services does support a mix between the interface based from Web Servics and and LINQ based querying that is supported by ADO.NET Data Services.

Reasons to Avoid: RIA Services leverages a lot of magic code generation to make it work and that is harder to debug than it should be. Integration with large enterprises is possible, its not as easy it as it should be.

"So Which Would You Suggest?"

While I paint this picture of data access in Silverlight with a broad brush, I still get the question to suggest one over the other. The fact remains that there isn't a right/wrong answer here. A lot of it depends on the environment, project and skillset of the developers. So, no...I won't tell you what I suggest because I don't know the requirements and environment you work in. That's why they pay you the big bucks to be a developer, right?

Comments:

Gravatar

"Reasons to Avoid: RIA Services leverages a lot of magic code generation to make it work and that is harder to debug than it should be"

Ado.Net DataServices use magic code generation (proxies) too, besides the code generated by RIA Services is very straingtforward, also the exposed service is REST based (not WS*) just like ADO.Net Data Services.

It's not hard at all to debug compared to Ado.Net Data Services.

Ria Services also has excelent validation story, ADO.Net DS has issues with serverside validation, lot's of missing needed functionality.

I've used all methods you describe so far and I would rate all technologies for small and medium up to large scale development and in between like this:

WS* - 5
Ado.Net DS - 4
RIA Services - 8

Cheers

Gravatar

What about some sort of remoting solution? Like WebOrb - similar to Flash Remoting. What are your feelings on that?

Gravatar

I am not familiar with that product.

Gravatar

For a database accessed exclusively via stored procedure (DBA requirement for database with sensitive data), how do these 3 data access layers compare? Reasons to use, reasons to avoid?

Gravatar

I've been looking for an article like this. Great work!

Gravatar

Thanks for the excellent post.

What are the query performance characteristics of the three options?

Presumably WS* comes out on top, whereas ADO.NET and RIA are roughly similar?

Gravatar

Web Services and the other two are pretty close. For small sizes Web services are slower (because of the larger cargo) whereas RIA/ANDS are on the slower side when larger...but all within performance measurements that I don't think perf is part of the discussion. At least with the tests that I did. Most perf is in the transport layer, not in the code layer.

Gravatar

RIA services are still a CTP right? Is it ready for reallife application?

Gravatar

Arik,

It is but I suspect it will be released soon.

Gravatar

This is the best and easy to understand posting in terms of developer trying to make a decision of which way to go.

Gravatar

Another possible addition to the Web Service category is RESTful services. Currently the largest avoid for RESTful services is that credentials or HTTP authorization is not supported or disabled in Silverlight.

Gravatar

You stated no suggestions would be given. Anyway, may I ask whether you see any benefit of .Net RIA Services comparing to ADO.Net Data Services for read-only scenarios( just querying data by multiple ways, joins are possible, and displaying in controls).

Gravatar

Thanks to Shawn for giving me a clear understanding about Accessing Data in Silverlight.
I agree with Pop and hence I would recommend to use .Net RIA services as it give you the flexibility to use WebServices as well as ADO.NET Data Services by creating single Silverlight Business Application.

Great work Shawn...!

Gravatar

Thanks for the post. Here is my opinion, not that it counts for much... if you need something that works now, stick with ASMX/WCF or code your own REST. After some digging, prototyping, and researching; ANDS, RIA, and WCF Rest Starter Kit are not ready for prime time, large scale applications. All of these technologies inject themselves heavily into your presentation logic, they are nearly impossible to mock, and unit testing is a down right pain.

SOAP has been working great for years. I can take all of my WCF/ASMX services and move them right into azure. I also have the control, and I can build new apps from these existing services, and I can mock and test these items in my presentation layer. If I was really brave, I could even roll my own bare bones "RESTful" services with MVP & WCF.

So if you need to build a real enterprise app, I would suggest that we stick to what we know (for now). Microsoft is moving too fast on these technologies to predict what the data access landscape will look like 3 months from now.

You can also use history to predict the future.... rdo,dao,mdac,ado, ado.net, linq, ..., and lets not forget com, dcom, mts, com+, enterprise services, remoting, WCF...

Gravatar

Any one who wants to implement these thing in LOB then, preformance is also a main thing to look after.Every buddy need the application to be first. you said its due to transporataion layer. so what you suggest to use to get good performance?

Gravatar

Any one who wants to implement these thing in LOB then, preformance is also a main thing to look after.Every buddy need the application to be first. you said its due to transporataion layer. so what you suggest to use to get good performance?

Gravatar

After reading this and several other commentaries, I'm trying to figure out why anyone would want to use Silverlight in an enterprise level business application? I agree with Cedric that it's just not ready as an alternative to a traditional ASP.Net N-Tier app. It sounds like it's great for small flashy apps, not serious business. Am I off the mark here? I am researching this because I have a client that wants their app built on Silverlight. His reasoning is "being concerned about interface design".

Gravatar

Craig,

I think you're a bit off the mark. In the enterprise I'd be hard pressed to recommend a pure web solution (ASP.NET/RoR/SL/Flex) as you have the resources in the enterprise typically to create richer experiences without having to build with the limitations of web apps.

Silverlight Line-of-business are for applications that need to be delivered through the firewall. If you are using ASP.NET to deliver enterprise apps inside the firewall, you're working too hard IMHO. Click-once is a better overall experience in those cases. Doesn't mean you can't build it as an N-Tier solution, but its just don't have to live with the limitations of port 80.

Gravatar

Shawn -- Great article. I really appreciate it. I made my choice. The option that is clearly best for my project requires is "Web Services: Interface-based Data Access". Do you happen to have a link to a simple CRUD code sample using ASMX web services and Silverlight 3. BTW, I also know that I should not use WCF or REST for reasons which you made clear with your "reasons to avoid", etc. Thank you. -- Mark Kamoski

Gravatar

I found RIA Services excellent to develop with, and with the Silverlight Business Application template it fits nicely. But.. here is my issue at this point. I've spent 2 full days trying to get my application onto a Windows Server 2003 with no luck. I have spent about 20 years in dev now, so have done all the typically tasks, mime types, etc. Still no luck.. Frustrating so much I may revert back to standard Web Services, :( I really want to roll out with RIA..

Gravatar

Nice article... maybe I just misunderstood you, but it is possible also in RIA to write LINQ queries in the client code. With your example, instead of

var riaQry = ctx.GetGamesQuery()
.Where(g => g.Price < 50m)
.OrderBy(g => g.Name);

you can write

var riaQry = from g in ctx.GetGamesQuery()
where g.Price < 50m
orderby g.Name
select g;

Gravatar

IMO, play with RIA services, but don't use it for anything "enterprise" related.

Gravatar

Interesting read.. How about updating the post keeping in mind, the latest releases :)

Gravatar

All -- I have to second what Rob L. states above. I think he is right in that "the largest avoid for RESTful services is that credentials or HTTP authorization is not supported or disabled in Silverlight". AFAIK, this state of affairs is true. If it is not true, then someone please post a correction. I am wondering now if Silverlight 4 has changed this? Anyone? Thank you. -- Mark Kamoski

Gravatar

Hi Shawn,
Nice post.. Now I get clear idea of what to use for Data Services...

Thanks a lot.......

Gravatar

Hi Shawn, All

First, great article.

We are currently in state of paralysis, trying to decide between WCF Servcies and RIA Services.

I am new to .net, so this article has really helped.

Our gut feeling is to go with WCF Servcies with SL, as we are dealing with a very large enterprise app (i can see/understand Cedric Bertolasio arguments) Also WCF gives better sepearation of layers and potential to reuse services in supporting different delivery channels down-track.

RIA Servcies is being considered for its code-generation /RAD capabilities; but we fear a lock-in to RIA Clients.

With the release of .net for and SL4 has any thing shifted significantly to allay these concerns and make the choice to go RIA easier?

Appreciate any comments and thoughts from the group.

regards
binyakub

Gravatar

This was really helpful. Do you think you might update it for VS2010/Silverlight 4?

Gravatar

is that any way to use silverlight 4 without using Entity framwork that mean ,use my own frame work class (Business base & Business Object)

Gravatar

Brian,

It has been updated. See my article from about a wek ago.

Gravatar

Mody,

You can use your own framework. Using WCF Web Services or RIA Services would allowyou to do that. To use WCF Data Services, you'd have to implement the LINQ interfaces as well as IUpdateable but usually going to RIA Services or Web Services is easier.


 



 
Save Cancel