Web Services and DataSets: Why the Bad Rap?


Why is everyone so down on using DataSets in .NET Web Services? Sure, I’ll admit that using DataSets directly as Web Service parameters are indeed a problem. But why throw the baby out with the bath water?

For the uninitiated, DataSets are a problem as Web Service parameters because XML that is automatically generated as the parameter is a DiffGram of the DataSet. Unfortunately DiffGrams are simply not interop-friendly. At the end of the day the obvious use of DataSets in .NET Web Services are simply a bad idea.

But if we deal with DataSets as XML instead of a class to be serialized we can actually achieve some real benefits. If you have experienced DataSets, you know that you can specify an .xsd as the schema of the DataSet. What that means is that you can deliver the contents of the DataSet with relevant schema as an XML document. Since the resulting XML document can refer to a specific schema, the consumers of the Web Service (whether they are using Java, WebSphere, or .NET) will receive a self-describing, strongly typed piece of information.

But how does this work? The trick is wrapping your DataSet in an XmlDataDocument. By specifying your Web Service method like so:


[WebMethod]
public XmlDocument GetAllTheData()
{
  return new XmlDataDocument(yourDataSet);
}

This works because the XmlDataDocument derives from XmlDocument so that the XmlSerializer serializes it as an XML document. Whether the 'yourDataSet' field is a TypedDataSet or just a DataSet with an .xsd specified for its schema, the Web Service will export it as vanilla XML that can be consumed by any number of clients.



Shawn
Shawn Wildermuth
Author, Teacher, and Coach



My Courses

pluralsight
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.0)
Using Visual Studio Code for ASP.NET Core Projects (new)
Implementing and Securing an API with ASP.NET Core
Building a Web App with ASP.NET Core, MVC6, EF Core and AngularJS
Building a Web App with ASP.NET5, MVC6, EF7, and AngularJS (Retired)
Best Practices in ASP.NET: Entities, Validation, and View Models
Webstorm Fundamentals
Front-End Web Development Quick Start
Lessons from Real World .NET Code Reviews
Node.js for .NET Developers

Application Name WilderBlog Environment Name Production
Application Ver 2.0.0.0 Runtime Framework .NETCoreApp,Version=v2.0
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.26020.03
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86